V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Oathbinder
V2EX  ›  React

React 通过 props 传递函数的问题

  •  
  •   Oathbinder · 2018-02-02 15:27:56 +08:00 · 5257 次点击
    这是一个创建于 2268 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2018-02-02 21:28:03 +08:00
    swirling
        1
    swirling  
       2018-02-02 16:00:02 +08:00 via iPhone
    我觉得应该是 a 报错 b 不报错才对吧
    50480350
        2
    50480350  
       2018-02-02 16:06:59 +08:00
    this.handleClick = this.handleClick.bind(this);
    brickyang
        3
    brickyang  
       2018-02-02 17:17:37 +08:00 via iPhone
    你在 childA 的 constructor() 里加上 this.foo = this.foo.bind(this) 试试
    brickyang
        4
    brickyang  
       2018-02-02 17:19:15 +08:00 via iPhone
    噢噢,眼花了,在 childB 的 constructor 里给 handleClick bind this 试试
    Oathbinder
        5
    Oathbinder  
    OP
       2018-02-02 17:47:56 +08:00
    @50480350 @brickyang
    绑定之后还是一样的错误,而且根据 React 的文档,如果使用箭头函数就不需要绑定了
    Mullvinn
        6
    Mullvinn  
       2018-02-02 17:54:58 +08:00
    跑了一下贴出来的代码,没发现报错,看看是不是其他哪里有问题
    yacolinqi
        7
    yacolinqi  
       2018-02-02 21:28:03 +08:00 via Android
    断点调试一下呗,或者在 handleClick 打印一下看看呗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1637 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:46 · PVG 00:46 · LAX 09:46 · JFK 12:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.