javascript 在按钮按下时更改文本 (React.js)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46737933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:53:25  来源:igfitidea点击:

Changing text on button push (React.js)

javascriptreactjs

提问by Spencer

I'm relatively new to using react.js. I have a series of button at the top of the div, and when each one of them is pushed I would like to display a different set of text. I have been able to create a function that is activated when a button is pressed (and test it with an alert), but I can't seem to figure out how to have it present a different set of text for each different button or how to pass it based on which button is pressed.

我对使用 react.js 比较陌生。我在 div 顶部有一系列按钮,当按下每个按钮时,我想显示一组不同的文本。我已经能够创建一个在按下按钮时激活的功能(并使用警报对其进行测试),但我似乎无法弄清楚如何让它为每个不同的按钮显示一组不同的文本或如何根据按下的按钮传递它。

class App extends Component {
   handleClick() {
     alert("Test");
   }

   render() {
     return (

  <body>
    <div class="App">
      <div class="floating-box">
          <div class="search-tickets">
            <button id="demo" class="color-button">Button 1</button>
            <button class="color-button button2">Button 2</button>
            <button class="color-button button3">Button 3</button>
            <button ref="test" class="color-button button4" onClick={this.handleClick}>Button 4</button>

            <h1 class="h1-text">Text</h1><br/>
            <h2>
            <br/>-123
            <br/>-456
            <br/
            </h2>

          </div>
      </div>
    </div>
  </body>
  );
}

export default App;

Ideally what I'm looking to do is have a different paragraph of text displayed below the buttons when each one of them are clicked. I've seen posts looking to change the button text or color, but not really impact a separate piece of text.

理想情况下,我想要做的是在单击每个按钮时在按钮下方显示不同的文本段落。我见过一些帖子希望更改按钮文本或颜色,但并没有真正影响单独的一段文本。

Any guidance on this would be incredibly helpful.

任何关于这方面的指导都会非常有帮助。

回答by Austin Greco

Use this.setStateto update a variable and then render based on that. The buttons have onClickwhich call the functions that update the state:

使用this.setState更新变量,然后渲染基于这一点。按钮具有onClick调用更新状态的函数:

class App extends React.Component {
  state = {
    text: 'something'
  }

  onClickButton1 = () => {
    this.setState({
      text: 'clicked 1'
    });
  }

  onClickButton2 = () => {
    this.setState({
      text: 'clicked 2'
    });
  }

  // etc...

  render() {
    return (
      <div>
        <button onClick={this.onClickButton1}>
          Button 1
        </button>
        <button onClick={this.onClickButton2}>
          Button 2
        </button>
        <h1>{this.state.text}</h1>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

回答by Steven Scaffidi

You can defined an array with the texts you want in order to make it concise. Use this.setState to keep track of what you clicked: https://codepen.io/sscaff1/pen/mBGLjm

您可以使用您想要的文本定义一个数组,以使其简洁。使用 this.setState 来跟踪你点击的内容:https://codepen.io/sscaff1/pen/mBGLjm

const texts = [
  'Text 1',
  'Text 2',
  'Text 3',
  'Text 4'
];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clickedText: ''
    }
  }

  handleClick = (i) => {
        this.setState({ clickedText: texts[i] });
  };

  render() {
    const { clickedText } = this.state;
    return (
      <div>
        {texts.map((text, i) => 
          <button key={i} onClick={() => this.handleClick(i)}>Click me {i + 1}</button>
        )}
        {clickedText && <p>I clicked on button with text: {clickedText}</p>}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));