我在使用以下代码时遇到问题:
我的组件:
class Landing extends Component {
state = {
loginMethod: '',
tournamentCode: -1,
}
}
我的常量:
const Code = () => (
<div className="" style={{marginTop: 20}}>
<input
className=""
style={{lineHeight: 1, height: 30, border:0, paddingLeft: 5}}
placeholder="Tournament Code"
onChange={e => this.setState({tournamentCode: e.target.value})} />
<Link to="/App">
<button className="" style={{marginLeft: 10, border: 0, outline:
'none', background: '#efefef', height: 30, width: 80}}> Enter </button>
</Link>
</div>
)
它们都位于同一个 Landing.js
文件中。
我知道我的问题是我尝试在 Landing 类之外执行 this.setState
。对于这个问题有什么解决办法吗?或者我应该有更好的方法来编程吗?
我还阅读了一些有关 React 中的 redux 和上下文的内容。其中哪一条是我最好的选择?或者有更简单的解决方案吗?
最佳答案
简短回答:不,你不能 setState
在组件之外。
长答案:您不能直接修改组件外部的状态,但您始终可以创建一个更改状态的方法,然后将其作为 props 传递给 <Code />
成分。示例代码(为简单起见,<Link />
组件已被删除)
import React, { Component } from "react";
import ReactDOM from "react-dom";
class Landing extends Component {
state = {
loginMethod: "",
tournamentCode: -1
};
onChange = e => {
this.setState({
tournamentCode: e.target.value
});
};
render() {
//You can use <></> or <React.Fragment></React.Fragment>
//I printed out the state to show you that it has been updated
return (
<>
<div>{this.state.tournamentCode}</div>
<Code onChange={this.onChange} />
</>
);
}
}
const Code = ({ onChange }) => (
<div style={{ marginTop: 20 }}>
<input
style={{ lineHeight: 1, height: 30, border: 0, paddingLeft: 5 }}
placeholder="Tournament Code"
onChange={onChange}
/>
<button
style={{
marginLeft: 10,
border: 0,
outline: "none",
background: "#efefef",
height: 30,
width: 80
}}
>
Enter
</button>
</div>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<Landing />, rootElement);
重要提示:不需要 Redux 或上下文。学习基础知识并尝试思考问题的最简单解决方案,然后进一步扩展。不是在这种情况下,但这是您应该应用的一个很好的学习方法
Codesandbox 供将来引用:https://codesandbox.io/s/n1zj5xm24
关于javascript - 在组件外部设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53597482/