我有一个组件YourInformation
:
class YourInformation extends React.Component{
constructor(props) {
super(props);
this.state = {
errors: {},
username:"",
alterEGO:"",
aboutYou:"",
stage:1,
blocking: false,
canSubmit: false
};
/**** binding to make context of this to class ***/
this.formValueChange = this.formValueChange.bind(this);
this.disableButton = this.disableButton.bind(this);
this.enableButton = this.enableButton.bind(this);
this.submitInformation = this.submitInformation.bind(this);
}
/**** function to handle change in form inputs ****/
formValueChange(event) {
event.preventDefault();
if (event.target.id == 'username') {
this.state.username = event.target.value;
} else if (event.target.id == 'alterEGO') {
this.state.alterEGO = event.target.value;
} else if (event.target.id == 'aboutYou') {
this.state.aboutYou = event.target.value;
}
return true;
}
/**** function to handle submit event ****/
submitInformation() {
let _that = this;
_that.setState({ blocking: true});
/***** fetch API for your information starts **********/
fetch(Constants.SERVER_URL + '/api/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
alterEGO: this.state.alterEGO,
aboutYou: this.state.aboutYou,
stage: this.state.stage,
}),
}).then(function (response) {
还有一个组件,即
class ProfileInformation extends React.Component{
constructor(props) {
super(props);
this.state = {
errors: {},
customUrl:"",
facebookLink:"",
youtubeLink:"",
instagramLink:"",
twitterLInk:"",
coverPic:"",
profilePic:"",
stage:3,
categories:[],
blocking: false,
canSubmit: false
};
/**** binding to make context of this to class ***/
this.formValueChange = this.formValueChange.bind(this);
this.disableButton = this.disableButton.bind(this);
this.enableButton = this.enableButton.bind(this);
this.submitProfile = this.submitProfile.bind(this);
this.getCategories = this.getCategories.bind(this);
}
我想访问"用户名,alterEGO,aboutYOU"从yourInformation
到ProfileInformation
,因为我需要以profileInformation
组件形式预填充这些值。
如何在不使用道具的情况下解决此问题,因为我无法将ProfileInformation
组件调入YourInformation
组件的render
方法?
答案 0 :(得分:1)
React并没有真正以这种方式工作。在反应中,您希望将中的数据设置为将使用该信息的最低父级。所以基本上如果你有2个组件处理相同的数据,这些数据应该由这些2的父组件管理,并通过props发送到这两个组件。我建议您阅读反应documentation以进一步了解。
如果您想全局访问数据,我会使用redux补充您的项目。 Redux允许您在存储所有数据的应用程序上拥有一个通用存储,并且您可以从许多组件访问它,因为它不仅存储在整个应用程序中而且存储在单个组件中。