简体   繁体   English

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

[英]React.js: How to append a component on click?

I'm new to React and I'm puzzled on something kind of basic.我是 React 的新手,我对一些基本的东西感到困惑。

I need to append a component to the DOM after the DOM is rendered, on a click event.在呈现 DOM 之后,我需要在单击事件上将一个组件附加到 DOM。

My initial attempt is as follows, and it doesn't work.我的初步尝试如下,它不起作用。 But it's the best thing I've thought to try.但这是我想过尝试的最好的事情。 (Apologies in advance for mixing jQuery with React.) (提前为将 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>
        );
      }
    };

Hopefully it's clear what I need to do, and I hope you can help me attain an appropriate solution.希望很清楚我需要做什么,我希望你能帮助我找到一个合适的解决方案。

Don't use jQuery to manipulate the DOM when you're using React.使用 React 时不要使用 jQuery 来操作 DOM。 React components should render a representation of what they should look like given a certain state; React 组件应该呈现给定状态下它们应该是什么样子的表示 what DOM that translates to is taken care of by React itself. React 本身会处理转换成的 DOM。

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down.您想要做的是将“决定渲染内容的状态”存储在链的更高位置,并将其向下传递。 If you are rendering n children, that state should be "owned" by whatever contains your component.如果您正在渲染n孩子,则该状态应该由包含您的组件的任何内容“拥有”。 eg:例如:

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>;

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.正如@Alex McMillan 所提到的,使用 state 来规定应该在 dom 中呈现的内容。

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true.在下面的示例中,我有一个输入字段,我想在用户单击按钮时添加第二个字段,onClick 事件处理程序调用 handleAddSecondInput() 将 inputLinkClicked 更改为 true。 I am using a ternary operator to check for the truthy state, which renders the second input field我正在使用三元运算符来检查真实状态,它呈现第二个输入字段

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM