我有两个组件,一个父组件和一个子组件,如下所示:
class Parent extends React.Component {
shuffle() {
...
}
blur() {
...
}
next() {
...
}
previous() {
...
}
render() {
return (
<Child Parent={this} />
);
}
}
class Child extends React.Component {
constructor(props) {
super();
this.state = {};
this._onShuffleClick = this._onShuffleClick.bind(props.Parent);
this._onPreviousClick = this._onPreviousClick.bind(props.Parent);
this._onNextClick = this._onNextClick.bind(props.Parent);
}
_onShuffleClick(event) {
event.preventDefault();
this.shuffled ? this.shuffle(false) : this.shuffle(true); // I can call parents method here as the 'this' context is the 'Parent'.
this.blur(event.target);
this.setState({test "test"}); //I can set the parents state here
}
_onPreviousClick(event) {
event.preventDefault();
this.previous();
this.blur(event.target);
}
_onNextClick(event) {
event.preventDefault();
this.next();
this.blur(event.target);
}
render() {
return (
<a className="shuffle" key={1} onClick={this._shuffleOnClick}>{this.props.Parent.props.html.shuffle}</a>,
<a className="previous" key={2} onClick={this._previousOnClick}>{this.props.Parent.props.html.previous}</a>,
<a className="next" key={3} onClick={this._nextOnClick}>{this.props.Parent.props.html.next}</a>,
);
}
}
将上下文(“this”关键字)作为 prop 传递是一种反模式吗? 从子级设置父级的状态是否不好?
如果我这样做,我就不必将很多单独的 Prop 传递给 child ,而且我还可以从 child 设置 parent 的状态。
最佳答案
您可以从子组件与父组件的状态
进行交互,但可能不是您尝试实现此目的的方式。
如果您想将父级的所有 props
发送给子级,您可以这样做:
<Child {...this.props} />
这样,您就不需要一次指定每个单独的prop
;相反,您只需将它们全部发送即可。查看扩展运算符 here和here了解更多信息。 MDN 上还有更多信息:
<小时/>The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.
如果您想从子级访问或修改父级的状态
,则必须稍微不同地执行此操作。通常,您会创建一个函数来与父级中的 state
进行交互,然后将该函数作为 prop
发送给子级。像这样:
父级:
_modifyState = (bar) => {
this.setState({foo: bar});
}
.....
<Child modifyState={this._modifyState} />
child :
this.props.modifyState("Hello world!");
上面的代码会将父组件中的 state.foo
设置为子组件中的字符串 Hello world!
。
如果您想访问所有state
变量,您可以将其作为prop
发送给子对象(整个对象),然后有一个函数(如上面)它修改整个状态(不仅仅是一个属性) - 取决于你真正想要什么。
关于javascript - 通过 props 传递 "this"上下文是反模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40422479/