简体   繁体   中英

switch components in react js

I'm doing a singlepage application and would like to switch a component.

Here is an image how it looks like:

在此处输入图片说明

If I click on the button in component 3, I will switch the component 3 with 5. So maybe like component 3 is a view of all projects and if I click on one project, I will see a detail view of the project with some information. I created two different components for this. All other components should stay at the same place.

Here is my code how I switch the components:

  this.state.detailVisible
      ? <ProjectDetailView/>
    : null

I'm not sure if is the correct react way to do it. Also I have two different css files for component 3 and 5. If I'm switching the two component, I have some class name irritations with my css.

If it's a better way to do it with routers? How is the react way to do it?

thanks for your help :)

It all depends on your needs, if you need to render both component3 and component5 then a route won't be much of a help.
If you need to render only one of them then a route can be handy.
as for the syntax i prefer this:
this.state.detailVisible && <ProjectDetailView/>

here is a simple example:

 const components = ["Component1", "Component2", "Component3"]; class Component extends React.Component { constructor(props) { super(props); this.state = { showDetails: false }; this.onComponentClicked = this.onComponentClicked.bind(this); } onComponentClicked(e) { this.setState({ showDetails: !this.state.showDetails }); } render() { const { name } = this.props; const { showDetails } = this.state; return ( <div> <div>Component{name}</div> <button onClick={this.onComponentClicked}>Toggle Details</button> {showDetails && <ComponentDetails name={name} />} </div> ); } } const ComponentDetails = ({ name }) => ( <div> <div>Details of component{name}</div> </div> ); class App extends React.Component { render() { return ( <div> <h2>Parent</h2> {components.map(c => { return ( <div> <Component name={c} /> <hr /> </div> ); })} </div> ); } } ReactDOM.render(<App />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

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