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

IT技术 javascript reactjs dom
2021-04-14 10:50:29

我是 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>
        );
      }
    };

希望很清楚我需要做什么,我希望你能帮助我找到一个合适的解决方案。

2个回答

使用 React 时不要使用 jQuery 来操作 DOM。React 组件应该呈现给定状态下它们应该是什么样子表示React 本身会处理转换成的 DOM。

您想要做的是将“决定渲染内容的状态”存储在链的更高位置,并将其向下传递。如果您正在渲染n子项,则该状态应该由包含您的组件的任何内容“拥有”。例如:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

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

const ChildComponent = props => <div>{"I am child " + props.number}</div>;
这对我有用(带有@ewindsor 的附录)!很棒的解决方案。
2021-05-22 10:50:29
我学到的一件事children是反应关键字。也就是说,我将children const定义的 inside重命名AppComponent,但是,无论如何,我仍然需要调用{this.props.children}inside ParentComponent
2021-05-22 10:50:29
@ewindsor oop!我很快就输入了,哈哈,谢谢 - 已修复
2021-05-24 10:50:29
很好的答案!我只会将 .bind(this) 添加到 this.onAddChild 以确保它可以调用 this.setState。
2021-06-02 10:50:29
@jayqui 是的 - 我本可以更清楚地说明这一点。您可以根据需要重命名 const,但是如果您像将 a<span>放入 a一样传递它们<p>,则可以通过this.props.children. 如果您像将href属性传递给<a>标签一样传递它们,那么您可以通过this.props.[attribute name].
2021-06-21 10:50:29

正如@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>
    );
  }
}
如果我想通过点击添加数百个 InputField 怎么办?
2021-05-26 10:50:29
@youneskhanbaba 但是当添加另一个组件时反应重新渲染所有这些组件时,这不会影响应用程序性能吗?
2021-06-15 10:50:29
@kabrice 保持一个列表处于状态,然后映射到该列表并显示一百个输入字段
2021-06-17 10:50:29