3

我有多个组件,在生命周期方法中具有相似的片段代码,并且在状态变量中有一些相似之处。有没有办法通过从一个父母继承或类似的东西来统一它们?

constructor(props) {
    super(props);
    this.state = {
        //state properties similar in all components, getting from redux
        //state properties specific for this component
    }
    // same code in many components
}

componentWillMount() {
    // same code in many components
    // code specific for this component
}

我可以在父“包装器”中使用子方法和道具吗?我可以从父级更改组件状态吗?

4

2 回答 2

3

您可以为此创建高阶组件(HOC),基本上,您只需使用重复的相同生命周期方法编写组件,然后在render()函数中,使用您想要的任何 HOC 内部状态参数调用this.props.children函数,您可以传递整个state和一个setState功能,因此您可以更改底层组件内的 HOC 状态。

例如:

  class HOC extends React.Component {
   constructor(props) {
     super(props);
     state = {
       someState: 'foo',
     };
   }

   componentWillMount() {
     console.log('i mounted!')
   }
   render() {
     return (
       <div>
         {this.props.children({ state: this.state, setState: this.setState })}
       </div>
     )
   }
 }

 const SomeComponent = () =>
   <HOC>
     {({ state, setState }) => (
       <div>
         <span>someState value: </span>
         <input 
           value={state.someState} 
           onChange={e => setState({ someState: e.target.value})} 
         />
       </div>
     )}
   </HOC>

你还可以用它做一些非常酷和有趣的事情,比如在你需要的时候连接你的 redux 状态的一部分:

import { connect } from 'react-redux';

const ProfileState = connect(
  state => ({ profile: state.profile }),
  null,
)(({ 
  profile, 
  children
  }) => ( 
  <div>
    {children({ profile })}
  </div>
));

const ProfilePage = () => (
  <div>
    Your name is:
    <ProfileState>
     {({ profile }) => (
       <span>{profile.name}</span>
     )}
    </ProfileState>
  </div>
);

是有关此技术的完整文档。

于 2018-06-07T10:41:33.143 回答
2

在这种情况下,您可以创建 HOC(高阶组件)。它看起来像这样:

/*
   A Higher Order Component is a function,
   that takes a Component as Input and returns another Component.

   Every Component that gets wrapped by this HOC
   will receive `exampleProp`,`handleEvent`, 
   plus all other props that get passed in.
*/

function WithCommonLogic(WrappedComponent) {
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        example: ''
      }
    }
    componentWillMount() {
      ...
      // Same code in many components.
    }
    callback = () => {
      /* Enhanced components can access this callback 
         via a prop called `handleEvent`
         and thereby alter the state of their wrapper. */
      this.setState({example: 'some val'})
    }
    render() {
      return <WrappedComponent 
          exampleProp={this.state.example}
          handleEvent={this.callback}
          {...this.props}
      />
  }
}


// You use it like this:

const EnhancedComponent1 = WithCommonLogic(SomeComponent);
const EnhancedComponent2 = WithCommonLogic(SomeOtherComponent);

现在所有的共享逻辑都进入了那个 HOC,然后包装了你想要与之共享的所有不同的组件。

请参阅React 文档以进一步阅读。

于 2018-06-07T10:59:48.397 回答