React Handle Interaction State Between Components
I have a simple component who show element onClick: class MyComponent extends React.Component { state = { isVisible : false } render() { cons
Solution 1:
You should have your component controlled, so move isVisble to props and and then assign it from MySuperComponent.
Also pass MyComponent a callback so it can inform the parent if it wants to change the state.
You'd want some data structure to store that states.
https://codepen.io/mazhuravlev/pen/qxRGzE
classMySuperComponentextendsReact.Component {
constructor(props) {
super(props);
this.state = {children: [true, true, true]};
this.toggle = this.toggle.bind(this);
}
render() {
return (
<div>
{this.state.children.map((v, i) => <MyComponentvisible={v}toggle={() => this.toggle(i)}/>)}
</div>
)
}
toggle(index) {
this.setState({children: this.state.children.map((v, i) => i !== index)});
}
}
classMyComponentextendsReact.Component {
render() {
const text = this.props.visible ? 'visible' : 'hidden';
return (<divonClick={this.props.toggle}>{text}</div>);
}
}
React.render(<MySuperComponent/>, document.getElementById('app'));
Solution 2:
You can check your code here, is this what you want. example
Post a Comment for "React Handle Interaction State Between Components"