简体   繁体   English

反应js-将值从子级传递给父级,然后传递给另一个子级?

[英]react js - passing a value from child to parent, then to another child?

Edit: Thanks for the responses guys. 编辑:谢谢你们的回答。 I've found the root of my problem here. 我在这里找到了问题的根源。 For some reason the code (I've inherited from others) is calling up my component multiple times, overwriting my values. 由于某种原因,代码(我已经从其他人继承来了)多次调用我的组件,覆盖了我的值。 I think I can take it from here. 我想我可以从这里拿走。 Thanks anyway guys. 谢谢大家。

My components are set up like this: 我的组件设置如下:

A
- B
- C

And I would like B, when triggered, to pass a value back to A and set a new state. 我希望B在被触发时将值传递回A并设置一个新状态。 Then, when an event is triggered, A would pass that value to C as a prop. 然后,当触发事件时,A会将该值传递给C作为道具。

So far, I've tried creating a function in A then pass it to B as a prop, as such: 到目前为止,我已经尝试在A中创建一个函数,然后将其作为prop传递给B,如下所示:

A: 

handler(){
    setState({value: someVal});
}

render(){
    <B func={this.handler}/>
    eventTriggered <C cProp={this.state.value}/>
}

However, as (I've found out that) setState() is asynchronous, when it is time for C to mount, this.state.value might not have the value from B assigned yet. 但是,由于(我发现)setState()是异步的,因此当该挂载C时,this.state.value可能尚未分配B中的值。

Perhaps my entire approach is wrong, but is there anyway of remedying this? 也许我的整个方法是错误的,但是是否有补救措施?

Thanks in advance. 提前致谢。

In your render() method, you could not render C until the event has been triggered and state has a value eg 在您的render()方法中,直到事件被触发并且状态具有值(例如,

render() {
    return (
        <B func={this.handler} />
        {eventTriggered && this.state.value &&
            <C cProp={this.state.value} />
        }
    )
}

EDIT: 编辑:

Make sure in component A you have: 确保在组件A中具有:

constructor(props) {
    super(props);
    this.handler = this.handler.bind(this);
}

typically, you can solve this kind of issue by using a second argument to setState (a function) 通常,您可以通过在setState (函数)中使用第二个参数来解决此类问题

eg 例如

handleClick(e){
  this.setState({value: e.target.value}, () => this.props.onChange(this.state.value))
}

the second function will only fire the onChange prop when the state is reconciled. 第二个功能只会在状态协调后触发onChange属性。 If you want to fire it earlier, send the raw value of e.target.value instead 如果您想更早将其触发,请改为发送e.target.value的原始值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM