样式未在组件中更新-React

时间:2018-07-02 13:54:48

标签: javascript reactjs

我有一个主要组件,当我将一个道具传递给另一个组件时,它不会更新样式。 display仍为none,但由于我已将prop更改为block,因此它的意思是更新为true。怎么了?

class Apps extends Component {
  constructor(props) {
    super(props);
    // Don't do this!
    this.state = { showing: true, Login: false, Signup: false, Members: false };
  }
  render() {
    return (
      <div>
        <div
          className="container"
          style={{ display: this.state.showing ? "block" : "none" }}
        >
          <div>A Single Page web application made with react</div>
        </div>
        <LoginComponent view={this.state.Login} />
        <div className="buttons">
          <a href="" ref="login" onClick={this.Login_onclick.bind(this)}>
            {this.state.Login ? "back" : "Login"}
          </a>
          <br />
        </div>
      </div>
    );
  }

  Login_onclick(e) {
    this.setState({ Login: !this.state.Login });
    e.preventDefault(); //alert(e.target.value);
    this.setState({ showing: !this.state.showing });
    // this.setState({ref: !ref});
  }
}

登录组件

class LoginComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: this.props.view
    };
  }
  render() {
    return (
      <div
        className="login"
        style={{ display: this.state.show ? "block" : "none" }}
      >
        <h3>Login</h3>
        <br />
        Username: <input type="text" ref="username" />
        <br />
        Password <input type="password" ref="password" />
        <button value="Login">Login</button>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

创建组件时,您正在设置this.state = { show: this.props.view };。此后更改view属性将无效。

如果您希望在道具更新时进行更新,则无需在show中设置state

class LoginComponent extends Component {
  render() {
    return (
      <div className="login" style={{ display: (this.props.view ? 'block' : 'none') }}>
        <h3>Login</h3><br/>
        Username: <input type="text" ref="username"/><br/>
        Password <input type="password" ref="password"/>
        <button value="Login" >Login</button>
      </div>
    ); 
  }
}