[英]How can I access a state of another file (and function) in React JS?
[英]React - How can I access a state/array that's in one .js file in a different .js file?
export default class Board extends React.Component {
constructor(props) {
super(props);
this.state = { board: ['?', '?', '?', '?', '?', '?', '?', '?', '?']};
this.counter = 0;
this.limit = 0;
}
我想在不同的js文件中访问带有这些问号(this.state)的板,例如...
import Board from './Board';
export default class Interface extends React.Component
{
constructor(props) {
super(props);
}
resetBoard()
{
Board.state.setState({ board: ['?', '?', '?', '?', '?', '?', '?', '?', '?']});
}
render()
{
return(
<header id="game-reset">
<h1 onClick={this.resetBoard}>Reset</h1>
</header>
);
}
}
对于丑陋的格式问题很抱歉,但本质上我正在尝试使用 Interface.js 中的 resetBoard() 函数将 Board.js 中的板重置回所有问号问题是,我需要访问“this.state”来自 Board.js 的板。 我知道这条线
Board.state.setState({ board: ['?', '?', '?', '?', '?', '?', '?', '?', '?']});
不起作用,因为我不完全理解访问该数组所需的语法。 我怎样才能访问第一个数组,以便我可以将它改回所有问号? 谢谢!
在 React 中无法访问另一个组件的状态。 即使有办法 - 也不推荐。
有两个选项可以解决您的问题:
正如 Mat 在他之前的评论中提到的, Component 的state
属于它自己。 组件可以通过props
将它的状态传递给它的子组件。
更新父组件状态的方法是在父组件中定义函数并将其作为props
传递给子组件。
因此,在您的示例中,它将类似于:
Board.js
class Board extends React.Component {
constructor(props) {
super(props);
this.state = { board: ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x']};
this.counter = 0;
this.limit = 0;
this.handleResetBoard = this.handleResetBoard.bind(this);
}
handleResetBoard() {
this.setState({
board: ['y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y']
});
}
render() {
return (
<div>
<h2>Interface</h2>
<Interface board={this.state.board} resetBoard={this.handleResetBoard} />
</div>
)
}
}
接口.js
import Board from './Board';
class Interface extends React.Component {
constructor(props) {
super(props);
}
render(){
return(
<header>
<pre>{JSON.stringify(this.props.board, null, 2)}</pre>
<button onClick={this.props.resetBoard}>Button</button>
</header>
);
}
}
看看这个: JSFiddle
我还鼓励您在此处阅读有关在何处保留状态的更多信息: https : //reactjs.org/docs/thinking-in-react.html#step-4-identify-where-your-state-should-live
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.