gpt4 book ai didi

javascript - React - 一种统一的方式,如果许多组件在生命周期方法中具有相同的代码段

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:30:05 26 4
gpt4 key购买 nike

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

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
}

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

最佳答案

您可以为此创建高阶组件 (HOC),基本上,您只需使用重复的相同生命周期方法编写组件,然后在 render() 函数中调用 this .props.children 函数与任何你想要的 HOC 内部状态参数,你可以传递整个 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 state 的一部分:

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

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

关于javascript - React - 一种统一的方式,如果许多组件在生命周期方法中具有相同的代码段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50739025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com