在React JS的两个组件之间切换的最有效方法是什么?

时间:2018-07-19 19:20:45

标签: reactjs

我已经看到了多个有关如何切换单个组件可见性的示例,但是在React中两个兄弟组件的可见性之间切换的最有效方法是什么?

3 个答案:

答案 0 :(得分:2)

我通常使用带有某种逻辑的单独函数来决定要显示的内容,并将该函数放置在主渲染函数中。以下面的代码为例:

String dir = Paths.get(MainController.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent().toString();
if (SystemUtils.IS_OS_WINDOWS) {
    System.load(current + "/lib/native_library.dll");
}   
else if (SystemUtils.IS_OS_MAC_OSX) {
    System.load(current + "/lib/native_library..dylib");
}
const FirstComponent = (props) => {
  
  return (
    <div className='first-class'>Hello, I am the first component!</div>
  )
}

const SecondComponent = (props) => {
  
  return (
    <div className='second-class'>And I am the second component!</div>
  )
}

class MainComponent extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      display: 'first'
    };
  }
  
  changeDisplay = () => {
    let { display } = this.state;
    this.setState({ display: display === 'first' ? 'second' : 'first' });
  }
  
  renderInner() {
    let { display } = this.state;
    
    if (display === 'first') {
      return <FirstComponent />
    } else if (display === 'second') {
      return <SecondComponent />
    }
  }
  
  render() {
    
    return (
      <div className='main-class'>
        <div className='button' onClick={this.changeDisplay}>Click me</div>
        {this.renderInner()}
      </div>
    );
  }
}


const root = document.getElementById('app');
ReactDOM.render(<MainComponent />, root);
  
  
  
.first-class {
  background: blue;
  display: inline-block;
}

.second-class {
  background: red;
  display: inline-block;
}

.main-class {
  margin-top: 10px
  width: 400px;
  height: 100px;
  background: #eee;
}

.button {
  padding: 5px 12px;
  border: 1px solid #ccc;
  background: #ddd;
  border-radius: 3px;
  display: inline-block;
  margin: 5px;
  cursor: pointer;
  user-select: none;
}

.button:hover {
  background: #ccc;
  border-color: #bbb;
}

答案 1 :(得分:1)

{toggle?<Component1 /> : <Component2 />}

似乎是最易读的方法。常见的是在加载组件时会显示一个假组件:

 {loaded?<Component /> : <Loading />}

答案 2 :(得分:0)

我已经有一段时间没有接触过图书馆了,但是我确信最好的方法是:

  1. 显然是两者的父组件
  2. 每个子组件都应以某种方式实现shouldComponentUpdate(),使得重新渲染仅在其实际需要更新时才触发。

这样,您可以切换它们两者而不必担心不必要的渲染