小编典典

React.js:如何在点击时添加组件?

reactjs

我是React的新手,对某种基本的东西感到困惑。

我需要在单击事件后呈现DOM之后将组件添加到DOM。

我最初的尝试如下,但是没有用。但这是我想尝试的最好的方法。(预先为将jQuery与React混合使用而道歉。)

    ParentComponent = class ParentComponent extends React.Component {
      constructor () {
        this.addChild = this.addChild.bind(this);
      }

      addChild (event) {
        event.preventDefault();
        $("#children-pane").append(<ChildComponent/>);
      }

      render () {
        return (
          <div className="card calculator">
            <p><a href="#" onClick={this.addChild}>Add Another Child Component</a></p>
            <div id="children-pane">
              <ChildComponent/>
            </div>
          </div>
        );
      }
    };

希望我已经清楚需要做什么,希望您能帮助我获得适当的解决方案。


阅读 741

收藏
2020-07-22

共1个答案

小编典典

正如@Alex McMillan所提到的那样,使用state来指示应在dom中呈现的内容。

在下面的示例中,我有一个输入字段,当用户单击按钮时,我想添加第二个字段,onClick事件处理程序调用handleAddSecondInput(),将inputLinkClicked更改为true。我正在使用三元运算符来检查真实状态,该状态将呈现第二个输入字段

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


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}
2020-07-22