下面是一个组件,它是一个输入按钮;它接受字符串输入。由于我使用的是create-react-app v3.0,因此我使用的是不带装饰器的mobx。因为我是mobx的新手,所以我不知道如何存储字符串值的状态,以便可以在其他组件中引用它。
下面是代码:
export class NumberButton extends Component {
constructor(props) {
super(props);
this.state = {
value: null
};
}
render() {
return (
<div>
<div className="content-section introduction">
<div className="feature-intro">
</div>
</div>
<div className="content-section implementation">
<div className="content-section implementation">
<h3 className="Number"> Number</h3>
{/*takes and stores input in value*/} <InputText type="text" value={this.state.NumberValue} onChange={(e) => this.setState({ NumberValue: e.target.value })} style={{width: "105%", height:"40px", }} />
</div>
</div>
</div>
);
}
}
如何获取值的状态并将其存储,以便可以在其他组件中使用它?感谢您的帮助。
答案 0 :(得分:0)
考虑使用Context在许多嵌套组件之间存储值。
答案 1 :(得分:0)
如果您要为此目的使用MobX,则可以创建单独的商店来控制其状态:
import { decorate, observable, action } from 'mobx';
class ButtonStore {
value = null;
setValue(value) {
this.value = value;
}
}
decorate(ButtonStore, {
value: observable,
setValue: action
})
export class NumberButton extends Component {
constructor(props) {
super(props);
}
render() {
const { store } = this.props;
return (
<div>
<div className="content-section introduction">
<div className="feature-intro">
</div>
</div>
<div className="content-section implementation">
<div className="content-section implementation">
<h3 className="Number"> Number</h3>
<InputText type="text" value={store.value} onChange={(e) => store.setValue(e.target.value) } style={{width: "105%", height:"40px", }} />
</div>
</div>
</div>
);
}
}
然后在父组件状态下,您只需实例化该存储即可:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
buttonStore: new ButtonStore()
}
}
render() {
return <NumberButton store={this.state.buttonStore} />
}
}
另一种更简单的方法是使用React Hooks处理该输入。
请注意,此代码未经测试,仅是一个想法!