代码之家  ›  专栏  ›  技术社区  ›  Genarito

React中嵌套组件的最佳实践

  •  0
  • Genarito  · 技术社区  · 7 年前

    class Component1 extends React {
        constructor(props) {
            super(props);
    
            this.state = {
                person: {
                    name: "Genaro",
                    age: 125
                }
            };
        }
    
        render() {
            return (
                <SubComponent
                    person={this.state.person}
                />
            );
        }
    }
    

    现在,我想让它呈现 SubComponent 当父类的状态改变时。这是由React自动完成的,但我可以通过两种方式完成:

    选项1(带状态):

    class SubComponent extends React {
        constructor(props) {
            super(props);
    
            this.state = {
                person: props.person
            };
        }
    
        componetWillReceiveProps(props) {
            this.setState({ person: props.person });
        }
    
        render() {
            return (
                <h1>Name: {this.state.person.name}</h1>
            );
        }
    }
    

    class SubComponente extends React {
        constructor(props) {
            super(props);
    
            this.person = props.person;
        }
    
        componetWillReceiveProps(props) {
            this.person = props.person;
        }
    
        render() {
            return (
                <h1>Name: {this.person.name}</h1>
            );
        }
    }
    

    我只能使用一个类(我需要调用很多实例方法)。这就是为什么 我不能这么做

    function SubComponent(props) {
        return (
            <h1>Name: {props.person.name}</h1> 
        );
    }
    

    两种方法都有效,但是:

    1. 哪个更好?在性能、可维护性等方面
    2. 我的两个选择是一个坏习惯吗?我怎样才能更好地处理这类问题?

    在这种情况下我找不到一个例子。

    提前谢谢,我的英语很抱歉

    1 回复  |  直到 7 年前
        1
  •  2
  •   devserkan    7 年前

    Subcomponent . 如果子组件的道具通过父组件更改,则子组件将重新渲染。所以,不要将它的道具设置为一个状态,而是直接使用道具。

    class Component1 extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          person: {
            name: "Genaro",
            age: 125
          }
        };
      }
    
      handleChange = e => {
        const { target } = e;
        this.setState( prevState => ({
          person: { ...prevState.person, name: target.value }
        }) )
      }
    
      render() {
        return (
          <div>
          <p>Change name</p>
          <input onChange={this.handleChange} />
            <SubComponent
              person={this.state.person}
            />
          </div>
        );
      }
    }
    
    class SubComponent extends React.Component {
      render() {
        return (
          <h1>Name: {this.props.person.name}</h1>
        );
      }
    }
    
    ReactDOM.render(<Component1 />, document.getElementById("root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="root"></div>