组件外部的setState



我遇到以下代码的问题:

我的组件:

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

长答案:您不能直接修改组件外部的状态,但您可以始终创建一个更改状态的方法,然后将其作为道具传递给<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

最新更新