[英]React.js - communication between different components in separeted files
我正在用React構建一個頁面,我有兩個組件,其中一個具有不同的功能。 首先是ProfileFill
,捕獲表單數據,其次是ProfileFillPercent
,該文件位於另一個文件中,並對表單填充進行平均。
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。 我試圖通過單例模式來傳遞它,就像這個Stack解釋一樣 ,但是它不起作用。 知道如何交流這兩個不是父母但共享相同數據的組件嗎? 在這種情況下,xpto是存儲ProfileFill狀態的數據。
認為你正在接近。
雖然有點困惑,所以我將簡要解釋這三種方式:
ProfileFill
(Child)需要將數據傳遞到ProfileFillPercent
(Parent)中 。
答:
您可以從父級傳遞一個作為道具的函數,該函數接受一個參數,並可用於在調用它時將數據從子級發送到父級。
您可以為兩者創建一個父容器 ,並從頂部將所需數據作為道具傳遞。
ProfileFillPercent
(父級)需要將數據傳遞到ProfileFill
(子級) 。
答:
您可以將其作為道具直接從父級傳遞。
您可以使用Redux (最好是較大的應用程序)
我有類似的情況,並開始使用Redux。
有很多帖子說您可能不需要Redux: https : //www.drinkingcaffeine.com/dan-abramov-you-might-not-need-redux/
對我來說,如果您的應用程序必須在兄弟組件之間傳遞許多數據,則可能需要使用Redux。
使用Redux可以保存客戶列表的狀態,並在每次加載組件時避免ajax。 因此,您可以減少代碼並更好地對其進行調試。
我從Dan Abramov的視頻教程開始研究Redux: https : //egghead.io/lessons/javascript-redux-writing-a-counter-reducer-with-tests
您可以將PubSub引入到React組件之間的通信中。 對於react,有react-pubsub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.