如何根据 ReactJS 上的条件更改按钮文本?

How do you change a button text depending on a condition on ReactJS?

提问人:orangesheep 提问时间:2/2/2021 更新时间:2/2/2021 访问量:4887

问:

ReactJS 新手在这里。我正在尝试学习 ReactJS 条件渲染。计划是在单击按钮时将按钮文本从“隐藏余额”更改为“显示余额”,反之亦然。我已经设法更改了布尔值的状态,但按钮没有更改其文本。 我做错了什么?

Account-Balance.jsx - 这是子组件

export default class ViewBalance extends Component{
    constructor(props){
        super(props);
    this.handleChange = this.handleChange.bind(this);
}

handleChange(){
    this.props.setPrivacy(this.props.setPrivacy);
}

render() {
    const buttonText = this.props.setPrivacy ? "Hide Balance" : "Show Balance";
    //true: balance is shown
    //false: balance is hidden

    return (
        <AccountBalDiv>
            <CurrentBal>Current Balance</CurrentBal>
                      //some code
            <div>
              <button onClick={this.handleChange}>{buttonText}</button>
            </div>
        </AccountBalDiv>
    );
    }
}

App.js - 这是父组件

    class App extends React.Component {
        constructor(props){
        super(props);

    this.state= {
      balance: 10000,
      setPrivacy: true
    }

    this.setPrivacy = this.setPrivacy.bind(this);
  }

  setPrivacy(){
    
    this.setState(oldState => ({
      setPrivacy: !oldState.setPrivacy
    }));

    console.log(this.state.setPrivacy)
  }

  render(){
    return (
      <AppDiv>
        <ViewBalance balance={this.state.balance}
                     setPrivacy={this.setPrivacy}/>
      </AppDiv>
       );
      }
     }

     export default App;
JavaScript ReactJS 布尔逻辑 Web前端

评论


答:

0赞 marcos 2/2/2021 #1

您只传递了方法(考虑到也有变量,这很令人困惑),但没有传递更改的结果。所以我会像这样重命名你的状态变量:setPrivacystate.setPrivacy

    class App extends React.Component {
        constructor(props){
        super(props);

    this.state= {
      balance: 10000,
      isPrivate: true
    }

    this.setPrivacy = this.setPrivacy.bind(this);
  }

  setPrivacy(){
    
    this.setState(oldState => ({
      isPrivate: !oldState.isPrivate
    }));

    console.log(this.state.setPrivacy)
  }

  render(){
    return (
      <AppDiv>
        <ViewBalance balance={this.state.balance}
                     setPrivacy={this.setPrivacy}
                     isPrivate={this.state.isPrivate}
       />
      </AppDiv>
       );
      }
     }

     export default App;

然后在子组件中访问它:

export default class ViewBalance extends Component{
    constructor(props){
        super(props);
    this.handleChange = this.handleChange.bind(this);
}

handleChange(){
    this.props.setPrivacy();
}

render() {
    const buttonText = this.props.isPrivate ? "Hide Balance" : "Show Balance";
    //true: balance is shown
    //false: balance is hidden

    return (
        <AccountBalDiv>
            <CurrentBal>Current Balance</CurrentBal>
                      //some code
            <div>
              <button onClick={this.handleChange}>{buttonText}</button>
            </div>
        </AccountBalDiv>
    );
    }
}