在不同的html元素中反映渲染组件

时间:2017-03-14 10:25:22

标签: javascript html reactjs components render

我对ReactJS很新。我想要两个按钮,在我页面上的同一div中的两个组件之间切换渲染。我开始时:

class NewComponent1 extends React.Component {
    render() {
        return (
           <div {...this.props}>
            new component1
           </div>
        );
    }
}
class NewComponent2 extends React.Component {
    render() {
        return (
           <div {...this.props}>
               new component2
           </div>
        );
    }
}
class Button1 extends React.Component {
    render() {
        return (
           <button {...this.props}>
               click1
           </button>
        );
    }  
}
class Button2 extends React.Component {
    render() {
        return (
          <button {...this.props}>
            click2
          </button>
        );
    }  
}
class App extends React.Component {
    constructor() {
        super();
        this.state = {
          clicked1: false,
          clicked2: false
        };
        this.handleClick1 = this.handleClick1.bind(this);
        this.handleClick2 = this.handleClick2.bind(this);
    }
    handleClick1() {
        this.setState({
            clicked1: true,
            clicked2: false
        });
    }
    handleClick2() {
     this.setState({
      clicked2: true,
      clicked1: false
   });
   }
   render() {
    return (
     <div>
      <Button1 onClick={this.handleClick1} />
      <Button2 onClick={this.handleClick2} />
      {this.state.clicked1 ? <NewComponent1 /> : null}
      {this.state.clicked2 ? <NewComponent2 /> : null}
    </div>
  );
  }
  };

  React.render(
  <App />,
  document.getElementById("root")
  );

我的推测结果很简单。如果我按Button1,我会使用MyComponent1在div中呈现id="area",如果按Button2,我会在MyComponent2“的div中呈现id="area,并且MyComponent1将不会呈现。依此类推。反之。如果MyComponent1存在,MyComponent2将在页面上呈现。 另外,Button1Button2会在id="root"的其他div中永久呈现。切换只应在id="area"的div中进行。

期待一些提示;)

0 个答案:

没有答案