programing

React.js : 클릭시 컴포넌트를 추가하는 방법은 무엇입니까?

coolbiz 2021. 1. 14. 22:59
반응형

React.js : 클릭시 컴포넌트를 추가하는 방법은 무엇입니까?


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

내가해야 할 일이 명확하고 적절한 해결책을 찾도록 도와 주시기를 바랍니다.


@Alex McMillan이 언급했듯이 state를 사용하여 dom에서 렌더링해야하는 것을 지정합니다.

아래 예제에는 입력 필드가 있고 사용자가 버튼을 클릭 할 때 두 번째 필드를 추가하고 싶습니다. onClick 이벤트 핸들러는 inputLinkClicked를 true로 변경하는 handleAddSecondInput ()을 호출합니다. 삼항 연산자를 사용하여 두 번째 입력 필드를 렌더링하는 진실 상태를 확인하고 있습니다.

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

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

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

ReferenceURL : https://stackoverflow.com/questions/35905988/react-js-how-to-append-a-component-on-click

반응형