我正在关注这篇文章(原始实现 Sibling Sibling): Update state cross component
该示例完美运行。但是当我尝试将每个类分离到每个 .js 文件时,然后使用导入/导出来相互调用/绑定(bind)。它(更新状态)不再起作用。 结构如下:
Sibling1.js
import React, { Component } from 'react';
<-- some declare style -->
export function updateText(text) {
this.setState({text})
}
export class Sibling1 extends Component {
render() {
return (
<div>
<div style={{ ...style.topLabel, color: secondaryColor }}>I am Sibling 1</div>
<input style={style.textBox} type="text"
placeholder="Write text" onChange={(e) => updateText(e.target.value)} />
</div>
)
}
}
Example.js
import React, { Component } from 'react';
import * as sibling1 from './Sibling1'; //is this good?
import {Sibling1} from './Sibling1'; //is this good?
<-- some declare style, variable -->
class Sibling2 extends Component {
constructor(props) {
super(props)
this.state = {
text: "Initial State"
}
sibling1.updateText = sibling1.updateText.bind(this) //is this good binding?
}
render() {
console.log('Sibling2.state : ', this.state);
return (
<div>
<div style={{ ...style.topLabel, color: primaryColor }}>I am Sibling 2</div>
<div style={style.label}>{this.state.text}</div>
</div>
)
}
}
class Example3 extends Component {
render() {
return (
<div>
<Sibling1 />
<Sibling2 />
</div>
)
}
}
export default Example3;
我只是希望 Sibling1 可以更改 Sibling2 的状态(就像最初的实现一样),但不能。 我想我的 bind(this) 没有绑定(bind)正确的上下文。 有人能告诉我原始实现(上面的文章)和我的方法(分离到多个 .js 文件)之间有什么区别吗?
最佳答案
updateText()
应该绑定(bind)到一个组件。我不确定您要在这里实现什么,但是如果上下文发生变化,updateText()
可能无法在 Sibling1 中工作。
您可以尝试在两个组件中绑定(bind) updateText()
(已在 Sibling2 中绑定(bind))。
import React, { Component } from 'react';
export function updateText(text) {
this.setState({text})
}
export class Sibling1 extends Component {
constructor() {
updateText = updateText.bind(this)
}
render() {
return (
<div>
<div style={{ ...style.topLabel, color: secondaryColor }}>I am Sibling 1</div>
<input style={style.textBox} type="text"
placeholder="Write text" onChange={(e) => updateText(e.target.value)} />
</div>
)
}
}
如果两个子组件需要共享状态并且只有处理程序传递给子组件,通常状态在父组件中控制。
关于javascript - 在 ReactJS 中从另一个组件更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52971183/