我不知道他们想用“React Context”的东西说什么——他们说的是希腊语,对我来说,但我是这样做的:
在同一页面上的函数之间携带值
在你的构造函数中,绑定你的setter:
this.setSomeVariable = this.setSomeVariable.bind(this);
然后在你的构造函数下面声明一个函数:
setSomeVariable(propertyTextToAdd) {
this.setState({
myProperty: propertyTextToAdd
});
}
当你想设置时,拨打this.setSomeVariable("some value");
(你甚至可以通过this.state.myProperty = "some value"; 逃脱)
想要领取的请拨打var myProp = this.state.myProperty;
使用alert(myProp); 应该会给你some value。
跨页面/组件传递值的额外脚手架方法
您可以将模型分配给this(技术上为this.stores),然后您可以使用this.state 引用它:
import Reflux from 'reflux'
import Actions from '~/actions/actions'
class YourForm extends Reflux.Store
{
constructor()
{
super();
this.state = {
someGlobalVariable: '',
};
this.listenables = Actions;
this.baseState = {
someGlobalVariable: '',
};
}
onUpdateFields(name, value) {
this.setState({
[name]: value,
});
}
onResetFields() {
this.setState({
someGlobalVariable: '',
});
}
}
const reqformdata = new YourForm
export default reqformdata
将其保存到名为stores 的文件夹中,为yourForm.jsx。
然后你可以在另一个页面中这样做:
import React from 'react'
import Reflux from 'reflux'
import {Form} from 'reactstrap'
import YourForm from '~/stores/yourForm.jsx'
Reflux.defineReact(React)
class SomePage extends Reflux.Component {
constructor(props) {
super(props);
this.state = {
someLocalVariable: '',
}
this.stores = [
YourForm,
]
}
render() {
const myVar = this.state.someGlobalVariable;
return (
<Form>
<div>{myVar}</div>
</Form>
)
}
}
export default SomePage
如果您使用以下函数在另一个组件中设置了this.state.someGlobalVariable:
setSomeVariable(propertyTextToAdd) {
this.setState({
myGlobalVariable: propertyTextToAdd
});
}
你在构造函数中绑定:
this.setSomeVariable = this.setSomeVariable.bind(this);
propertyTextToAdd 中的值将使用上面显示的代码显示在 SomePage 中。