【问题标题】:React.js: How to append a component on click?React.js:如何在点击时附加组件?
【发布时间】:2016-06-24 16:15:47
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs dom


    【解决方案1】:

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

    您想要做的是将“决定渲染内容的状态”存储在链的更高位置,并将其向下传递。如果您正在渲染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>;
    

    【讨论】:

    • 很好的答案!我只会将 .bind(this) 添加到 this.onAddChild 以确保它可以调用 this.setState。
    • 这对我有用(带有@ewindsor 的附录)!很棒的解决方案。
    • 我学到的一件事是children 是一个反应关键字。也就是说,我重命名了AppComponent内部定义的childrenconst,但是无论如何,我仍然需要在ParentComponent内部调用{this.props.children}
    • @ewindsor 哎呀!我很快就输入了,哈哈,谢谢你 - 修复了
    • @jayqui 是的 - 我本可以更清楚地说明这一点。您可以根据需要重命名 const,但如果您像在 &lt;p&gt; 中放置 &lt;span&gt; 一样传递它们,则可以通过 this.props.children 访问它们。如果您像将href 属性传递给&lt;a&gt; 标记一样将它们传递,那么您可以通过this.props.[attribute name] 访问它们。
    【解决方案2】:

    正如@Alex McMillan 提到的,使用状态来指示应该在 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怎么办?
    • @kabrice 保持一个列表处于状态,然后映射到该列表并显示一百个输入字段
    • @youneskhanbaba 但是当添加另一个组件时重新渲染所有这些组件时,这不会影响应用程序的性能吗?
    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 2011-08-13
    • 2020-11-11
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多