gpt4 book ai didi

javascript - react .js : Communication between two children of the same parent?

转载 作者:行者123 更新时间:2023-11-29 15:29:04 24 4
gpt4 key购买 nike

我有一个父组件:Previewer,它呈现两个子组件。

class Previewer extends Component {
render() {
return (
<AudioPlayer />
<SubtitleRow />
);
}
}

当用户点击 SubtitleRow 时,它应该传递变量,例如startTimeEndTime,到 AudioPlayer,它应该播放音频。

我读过 official documentation :

For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. Flux pattern is one of the possible ways to arrange this.

我觉得他们是亲戚( sibling ),那么,有没有其他的方式来实现他们的沟通呢?

根据 JavaScript the Good Parts 或某些 JavaScript 设计模式,不推荐使用全局事件或变量。

最佳答案

您可以使用状态将变量传递给 AudioPlayer 组件。然后在您的 SubtitleRow 组件中,您可以调用函数 this.props.onClick(startTime, endTime)

class Previewer extends Component {
constructor() {
this.state = { 'startTime': 0, 'endTime' : 0 };
this.handleClick= this.handleClick.bind(this);
}

handleClick(startTime, endTime) {
this.setState({
'startTime': startTime,
'endTime': endTime
});
}

render() {
return (
<AudioPlayer startTime="{this.state.startTime}" endTime="{this.state.endTime}"/>
<SubtitleRow onClick="{this.handleClick}" />
);
}
}

关于javascript - react .js : Communication between two children of the same parent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36627600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com