Reputation: 4542
I have a parent component: Previewer
which renders two children.
class Previewer extends Component {
render() {
return (
<AudioPlayer />
<SubtitleRow />
);
}
}
When the user clicks on SubtitleRow
, it should pass variables, e.g. startTime
and EndTime
, to AudioPlayer
, which should play audio.
I've read the 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.
I think they have a relationship (siblings), so, is there any way else to implement their communication?
Global event or variable is not recommended, according to JavaScript the Good Parts or something JavaScript design patterns.
Upvotes: 3
Views: 1317
Reputation: 18113
You could use the state to pass the variables to the AudioPlayer component. Then in your SubtitleRow component you can call the function 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}" />
);
}
}
Upvotes: 1