【问题标题】:How can I print multiiple text areas when clicking on a button in reactjs单击reactjs中的按钮时如何打印多个文本区域
【发布时间】:2020-12-01 20:50:09
【问题描述】:

在我的 reactjs 类组件中,我想创建一个按钮,每次单击它时都会打开一个新的文本区域(例如,当我单击 5 次时,它应该打开 5 个文本区域)。在当前结果中,它只打开一个文本区域。

因此,在第一步中,我创建了一个值为 0 的状态,并创建了一个应该改变状态的函数:

// InitialState
  state = {
    value: 0,
  };

onChange() {
    this.setState({
      value: this.state.value + 1,
    });
  }

在下一步中,我渲染了一个按钮并创建了 if 语句来显示文本区域(这不起作用):

render() {
    return (
      <div>
        <IconButton onClick={this.onChange.bind(this)}>
          <AddCircleOutlineIcon />
        </IconButton>
        <br />
        {this.state.value >= 1 ? this.showTextArea() : null}
      </div>
    );
  }

这是我的 showTextArea 函数:

showTextArea = () => {
    return (
      <textarea
        placeholder={this.state.placeholder}
        value={this.state.value}
        onChange={this.onChange1.bind(this)}
        rows="2"
        style={{ fontSize: "18px" }}
        onFocus={(e) => (e.target.placeholder = "")}
        onBlur={(e) => (e.target.placeholder = this.state.placeholder)}
      />
    );
  };

【问题讨论】:

    标签: javascript reactjs react-state react-state-management


    【解决方案1】:

    你的条件是错误的。 this.state.value &gt;= 1 应该是这样的,因为在第一个文本框打开并单击按钮后,您的按钮值为 2,第一个文本框将隐藏

    【讨论】:

      【解决方案2】:

      这可以仅使用单个条件来实现。用 for 循环改变你的渲染方法:

      render() {
          return (
              <div>
                  <IconButton onClick={this.onChange.bind(this)}>
                      <AddCircleOutlineIcon />
                  </IconButton>
                  <br />
                  {
                      for (let i = 0; i < this.state.value; i++) {
                          {this.showTextArea()}
                      }
                  }
              </div>
          );
      }
      

      【讨论】:

      • 好的,谢谢。但是,当我更改此代码时,它只会打开我的文本区域。你能找出任何其他错误吗,也许是在我的 showTextArea() 函数中,如下所示:showTextArea = () =&gt; { return ( &lt;textarea placeholder={this.state.placeholder} value={this.state.value} onChange={this.onChange1.bind(this)} rows="2" style={{ fontSize: "18px" }} onFocus={(e) =&gt; (e.target.placeholder = "")} onBlur={(e) =&gt; (e.target.placeholder = this.state.placeholder)} /&gt; ); };
      • @RainerWinkler 你需要在状态值上运行一个循环来绘制没有文本区域。请参阅上面的编辑示例。
      • 好的,非常感谢,这已经很有帮助了。似乎反应渲染不允许使用函数,而是使用地图函数。我会看看这是如何工作的。
      猜你喜欢
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多