V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Oathbinder
V2EX  ›  React

React 通过 props 传递函数的问题

  •  
  •   Oathbinder · Feb 2, 2018 · 6166 views
    This topic created in 3009 days ago, the information mentioned may be changed or developed.
    class Parent extends Component {
        constructor(props) {
        	super(props);
        	this.state = { "id": "1" };
        }
        
        setIdFromChildA = (id) => this.setState({ "id": id });
        setIdFromChildB = (id) => this.setState({ "id": id });
        
        render() {
        	return (
        	    <ChildA id={this.state.id} setId={this.setIdFromChildA} />
        	    <ChildB id={this.state.id} setId={this.setIdFromChildB} />
            );
        }
    }
    
    class ChildA extends Component {
    	constructor(props) {
        	super(props);
        	this.state = {...};
        }
        
        componentDidMount() {
        	this.foo()
        }
        
        foo() {
        	this.props.setId("2");
        }
    }
    
    class ChildB extends Component {
        constructor(props) {
        	super(props);
        	this.state = {...};
        }
        
        handleClick = (e) => {this.props.setId("2")};
        
        render() {
        	return (
                <button type="button" onClick={this.handleClick} />
        	);
    }
    

    现在的问题是 ChildA 调用 setId 没有问题但是 ChildB 在调用时会报错TypeError: _this.props.setId is not a function。A 和 B 的区别在于一个是在componentDidMount()中执行另一个是 onClick 事件触发,是因为这个原因吗?

    7 replies    2018-02-02 21:28:03 +08:00
    swirling
        1
    swirling  
       Feb 2, 2018 via iPhone
    我觉得应该是 a 报错 b 不报错才对吧
    50480350
        2
    50480350  
       Feb 2, 2018
    this.handleClick = this.handleClick.bind(this);
    brickyang
        3
    brickyang  
       Feb 2, 2018 via iPhone
    你在 childA 的 constructor() 里加上 this.foo = this.foo.bind(this) 试试
    brickyang
        4
    brickyang  
       Feb 2, 2018 via iPhone
    噢噢,眼花了,在 childB 的 constructor 里给 handleClick bind this 试试
    Oathbinder
        5
    Oathbinder  
    OP
       Feb 2, 2018
    @50480350 @brickyang
    绑定之后还是一样的错误,而且根据 React 的文档,如果使用箭头函数就不需要绑定了
    Mullvinn
        6
    Mullvinn  
       Feb 2, 2018
    跑了一下贴出来的代码,没发现报错,看看是不是其他哪里有问题
    yacolinqi
        7
    yacolinqi  
       Feb 2, 2018 via Android
    断点调试一下呗,或者在 handleClick 打印一下看看呗
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   861 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 22:19 · PVG 06:19 · LAX 15:19 · JFK 18:19
    ♥ Do have faith in what you're doing.