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

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

这里是 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;

您只传递了 setPrivacy 方法(考虑到还有 state.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>
    );
    }
}