React 通过 props 传递函数的问题

2018-02-02 15:27:56 +08:00
 Oathbinder
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 事件触发,是因为这个原因吗?

5266 次点击
所在节点    React
7 条回复
swirling
2018-02-02 16:00:02 +08:00
我觉得应该是 a 报错 b 不报错才对吧
50480350
2018-02-02 16:06:59 +08:00
this.handleClick = this.handleClick.bind(this);
brickyang
2018-02-02 17:17:37 +08:00
你在 childA 的 constructor() 里加上 this.foo = this.foo.bind(this) 试试
brickyang
2018-02-02 17:19:15 +08:00
噢噢,眼花了,在 childB 的 constructor 里给 handleClick bind this 试试
Oathbinder
2018-02-02 17:47:56 +08:00
@50480350 @brickyang
绑定之后还是一样的错误,而且根据 React 的文档,如果使用箭头函数就不需要绑定了
Mullvinn
2018-02-02 17:54:58 +08:00
跑了一下贴出来的代码,没发现报错,看看是不是其他哪里有问题
yacolinqi
2018-02-02 21:28:03 +08:00
断点调试一下呗,或者在 handleClick 打印一下看看呗

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/427992

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX