我正在用React构建一个页面,我有两个组件,其中一个具有不同的功能。首先,ProfileFill
,捕获表单数据,第二个,ProfileFillPercent
,这是在另一个文件中,并作出表格填充的平均值。React.js - 分离文件中不同组件之间的通信
ProfileFill.js:
import React from 'react';
import ReactDOM from 'react-dom';
export const CustomerFill = React.createClass({
handleChange() {
const customerName = this.customerName.value;
const customerCPF = this.customerCPF.value;
this.props.onUserInput(customerName, customerCPF);
},
render(){
const {customerName, customerCPF} = this.props;
return(
<div>
<div className="form-group col-sm-12 col-md-5">
<label htmlFor="inputName">Nome do segurado:</label>
<input
ref={(r) => this.customerName = r}
type="text"
className="form-control"
placeholder="Insira o nome do segurado"
value={customerName}
onChange={this.handleChange}
/>
</div>
<div className="form-group col-sm-12 col-md-5">
<label htmlFor="inputName">CPF do segurado:</label>
<input
ref={(r) => this.customerCPF = r}
type="number"
className="form-control"
placeholder="Insira o CPF do segurado"
value={customerCPF}
onChange={this.handleChange}
/>
</div>
</div>
)
}
});
export const ProfileFill = React.createClass({
getInitialState() {
return{
customerName: '',
customerCPF: '',
};
},
handleUserInput(customerName, customerCPF) {
this.setState({
customerName: customerName,
customerCPF: customerCPF,
});
},
render(){
const { customerName, customerCPF } = this.state;
this.xpto = this.state;
console.log(this.xpto);
return(
<div>
<div className="lateral-margin">
<h2>INFORMAÇÕES PESSOAIS</h2>
</div>
<div id="profile-fill" className="intern-space">
<form id="form-space">
<CustomerFill
customerName={customerName}
customerCPF={customerCPF}
onUserInput={this.handleUserInput}
/>
</form>
</div>
</div>
);
}
});
ReactDOM.render(
<ProfileFill />,
document.getElementById('fill-container')
);
export default ProfileFill;
ProfileFillPercent.js:
import React from 'react';
import ReactDOM from 'react-dom';
import ProfileFill from './profileFill.js';
console.log(ProfileFill.xpto);
export const ProfileFillPercent = React.createClass({
render() {
//things happen here
}
});
我创建一个变量的ProfileFill
这一个元素,我需要把它传递给ProfileFillPercent是在另一个文件。我试图通过它与单身模式,如this Stack explanation,但它不起作用。任何想法我怎么能沟通这两个组件不是父母,但共享相同的单一数据? 在这种情况下,xpto是存储ProfileFill状态的数据。
感谢您的帮助。我正在考虑这个问题,我将立即着手。感谢您提供这个视频建议。 :) – Aipi
欢迎你:)我开始使用Redux的时间太晚了,所以迁移变得越来越大,越来越困难,但是我控制着更好的状态并减少了很多我的代码只迁移了3个组件 –
如果你想支付pluralsight,有一个es6的伟大过程(将你的代码从es5迁移到es6也会很好),React,Redux和Webpack与Cory House。开始试用并查看本课程:https://www.pluralsight.com/ –