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

JavaScript React.js

泡芙Near

2020-03-19

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

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

第2393篇《React.js:如何在点击时添加组件?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Tom凯飞云 2020.03.19

使用React时,请勿使用jQuery来操作DOM。反应的组分应该呈现的表示,他们应该是什么样子给予一定的状态; 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>;

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android