programing

React.js:클릭 시 컴포넌트를 추가하는 방법

instargram 2023. 4. 2. 09:43
반응형

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

제가 해야 할 일이 명확해졌으면 좋겠고, 적절한 솔루션을 얻을 수 있도록 도와주셨으면 합니다.

React를 사용할 때는 jQuery를 사용하여 DOM을 조작하지 마십시오.리액트 컴포넌트는 특정 상태가 되었을 때 어떤 모습이어야 하는지 나타내야 합니다.즉, 어떤 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>;

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

다음 예에서는 입력 필드가 있는데 사용자가 버튼을 클릭하면 onClick 이벤트핸들러가 handleAddSecondInput()을 호출하여 inputLinkClicked를 true로 변경합니다.나는 두 번째 입력 필드를 렌더링하는 truthy 상태를 확인하기 위해 3진 연산자를 사용하고 있습니다.

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

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

반응형