d
k
p
l
u
s

react条件渲染

function WarningTip(props) {
  if (!props.warn) {
    return null;
  }
  return (
    <h1 className = 'warning'>warning</h1>
  );
}

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isWarningOn: false};
    this.handleWarn = this.handleWarn.bind(this);
  }
  handleWarn() {
    this.setState(prevState => ({
      isWarningOn: !prevState.isWarningOn
    }));
  }
  render() {
    return (
      <div>
        <WarningTip warn={this.state.isWarningOn}/>
        <button onClick={this.handleWarn}>{this.state.isWarningOn? 'on':'off'}</button>
      </div>
    );
  }
}
let root = document.getElementById('root');
ReactDOM.render(<Hello />,root);
posted @ 2018-04-18 15:48  dkplus  阅读(142)  评论(0编辑  收藏  举报