简体   繁体   中英

Show sibling components reactJs

I'm new on react world, I would show components from sibling components. I have parent component:

import Toast from './components/Toast/Toast'
class App extends Component {
    constructor(){
        super();
        this.state = {
            showToast:false
        };
    }   
  render() {
    return (
       <div id="cont">
          <Toast showToast={this.state.showToast}/>
          <Header />
        </div>

    );
  }
}

In my Toast component:

class Toast extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        const showToast = this.props.showToast;

        let toast = null;
        if (showToast) {
          toast = <div className="visible">Toast Ok</div>;
        }else{
            toast = null;
        } 

        return (
          <div>
            {toast}
          </div>
        );
      }
}

export default Toast;

And in my Header component I have:

class Header extends Component {
    render() {
       return (
         <button> // With click, show toastComponents so setState parent </button>
       )
    }

So if I click on button I would set state key showToast for show my components.

You can pass a function down to your <Header> component, then call it when the button is clicked.

let showToast = () => this.setState({ showToast: true });
// ...
<Toast showToast={this.state.showToast}/>
<Header onClick={showToast}>

Then all you need to do is pass this prop through to the click handler inside <Header> .

<button onClick={this.props.onClick}>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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