developer tip

React에 자식 컴포넌트를 동적으로 추가

copycodes 2020. 11. 25. 08:06
반응형

React에 자식 컴포넌트를 동적으로 추가


내 목표는 페이지 / 상위 구성 요소에 동적으로 구성 요소를 추가하는 것입니다.

다음과 같은 몇 가지 기본 예제 템플릿으로 시작했습니다.

main.js :

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);
ReactDOM.render(<SampleComponent name="SomeName"/>, document.getElementById('myId'));

App.js :

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <div id="myId">myId div</div>
            </div>

        );
    }

});

SampleComponent.js :

var SampleComponent = React.createClass({
    render: function() {
        return (
            <div>
                <h1>Sample Component! </h1>
            </div>
        );
    }
});

여기는 템플릿에 미리 작성된 노드에 SampleComponent마운트됩니다 . 하지만 앱 구성 요소에 무제한의 구성 요소를 추가해야하는 경우 어떻게해야합니까? 분명히 거기에 필요한 모든 div를 가질 수는 없습니다 .<div id="myId"></div>App.js

일부 튜토리얼을 읽은 후에도 구성 요소가 동적으로 생성되고 부모 구성 요소에 추가되는 방법을 아직 이해하지 못했습니다. 그것을하는 방법은 무엇입니까?


다음과 같이 구성 요소를 자식으로 전달해야합니다.

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
    <App>
        <SampleComponent name="SomeName"/> 
    <App>, 
    document.body
);

그런 다음 구성 요소의 본문에 추가합니다.

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                {
                    this.props.children
                }
            </div>
        );
    }
});

HTML 코드를 수동으로 조작 할 필요가 없습니다. React가 자동으로 수행합니다. 일부 하위 구성 요소를 추가하려면 props 또는 상태를 변경하면됩니다. 예를 들면 :

var App = React.createClass({

    getInitialState: function(){
        return [
            {id:1,name:"Some Name"}
        ]
    },

    addChild: function() {
        // State change will cause component re-render
        this.setState(this.state.concat([
            {id:2,name:"Another Name"}
        ]))
    }

    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <button onClick={this.addChild}>Add component</button>
                {
                    this.state.map((item) => (
                        <SampleComponent key={item.id} name={item.name}/>
                    ))
                }
            </div>
        );
    }

});

첫째, 나는 document.body를 사용하지 않을 것 입니다. 대신 빈 컨테이너를 추가하십시오.

index.html:

<html>
    <head></head>
    <body>
        <div id="app"></div>
    </body>
</html>

그런 다음 <App />요소 만 렌더링하도록 선택합니다 .

main.js:

var App = require('./App.js');
ReactDOM.render(<App />, document.getElementById('app'));

내에서 App.js다른 구성 요소를 가져오고 DOM 렌더링 코드를 완전히 무시할 수 있습니다.

App.js:

var SampleComponent = require('./SampleComponent.js');

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component!</h1>
                <SampleComponent name="SomeName" />
            </div>
        );
    }
});

SampleComponent.js:

var SampleComponent = React.createClass({
    render: function() {
        return (
            <div>
                <h1>Sample Component!</h1>
            </div>
        );
    }
});

그런 다음을 사용하여 필요한 구성 요소 파일로 가져 와서 여러 구성 요소와 프로그래밍 방식으로 상호 작용할 수 있습니다 require.


첫 번째 경고 : React에서 관리하는 DOM을 절대로 조작해서는 안됩니다. ReactDOM.render(<SampleComponent ... />);

React를 사용하면 메인 앱에서 직접 SampleComponent를 사용해야합니다.

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);

The content of your Component is irrelevant, but it should be used like this:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <SampleComponent name="SomeName"/>
            </div>
        );
    }
});

You can then extend your app component to use a list.

var App = React.createClass({
    render: function() {
        var componentList = [
            <SampleComponent name="SomeName1"/>,
            <SampleComponent name="SomeName2"/>
        ]; // Change this to get the list from props or state
        return (
            <div>
                <h1>App main component! </h1>
                {componentList}
            </div>
        );
    }
});

I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.

https://facebook.github.io/react/index.html


Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

참고URL : https://stackoverflow.com/questions/36651583/dynamically-add-child-components-in-react

반응형