demo要求:
在上面的input框內(nèi)輸入大寫單詞溯乒,下面的input框內(nèi)會自動展示出相應(yīng)的小寫單詞,
同理在下面的input框內(nèi)輸入小寫單詞确虱,上面的input框內(nèi)展示出相應(yīng)的大寫單詞。
圖片展示:
代碼展示:
import React from "react";
import ReactDOM from "react-dom";
const words={
upperCase:"upper",
lowerCase:"lower"
}
//將輸入的單詞轉(zhuǎn)化位大寫
function toUpper(input){
return input.toUpperCase();
}
//將輸入的單詞轉(zhuǎn)化為小寫
function toLower(input){
return input.toLowerCase();
}
// 定義子組件WordsInput
class WordsInput extends React.Component {
constructor(props){
super(props);
this.handleWordsInput=this.handleWordsInput.bind(this);
}
handleWordsInput(e){
this.props.onInputChange(e.target.value) //利用props屬性調(diào)用父組件傳過來的方法
}
render(){
const type=this.props.type;
const value=this.props.value;
return (
<form action="#">
<legend>請輸入{words[type]==="upper"?"大寫":"小寫"}字母</legend>
<input
value={value}
onChange={this.handleWordsInput}
/>
</form>
)
}
}
// 定義父組件InputChange
class InputChange extends React.Component {
constructor(props){
super(props);
this.handleUpperCase=this.handleUpperCase.bind(this);
this.handleLowerCase=this.handleLowerCase.bind(this);
this.state={
type:"upper",
text:""
}
}
handleUpperCase(value){
const text=toUpper(value)
this.setState({
type:"upper",
text //es6語法:鍵與值相同時可省略值
})
}
handleLowerCase(value){
const text=toLower(value);
this.setState({
type:"lower",
text //es6語法:鍵與值相同時可省略值
})
}
render(){
const value=this.state.text;
const type=this.state.type;
const upperCase= type==="lower"?toUpper(value):value; //保證upperCase變量永遠存儲大寫單詞
const lowerCase= type==="upper"?toLower(value):value; //保證lowerCase變量永遠存儲小寫單詞
return (
<div>
<WordsInput
type="upperCase"
value={upperCase} //保證該input框內(nèi)永遠展示出大寫單詞
onInputChange={this.handleLowerCase}
/>
<WordsInput
type="lowerCase"
value={lowerCase} //保證該input框內(nèi)永遠展示小寫單詞
onInputChange={this.handleUpperCase}
/>
</div>
)
}
}
ReactDOM.render(
<InputChange />,
document.getElementById("example")
代碼解讀:
首先定義了兩個函數(shù)toUpper
,toLower
,分別將輸入的單詞轉(zhuǎn)化為相應(yīng)的大小寫單詞
其次定義了一個父組件InputChange
及子組件WordsInput
,在子組件內(nèi)利用props屬性接受來自父組件傳過來的type
,value
,onInputChange
屬性
在子組件WordsInput
內(nèi),根據(jù)父組件內(nèi)傳入的屬性type
值的不同渲染出不同的文本斯够,并在不同的input
框內(nèi)綁定相應(yīng)的大小寫單詞,注冊onChange
事件,當input
框內(nèi)文本發(fā)生改變時读规,調(diào)用該事件所綁定的函數(shù)handleWordsInput
抓督,在handleWordsInput
函數(shù)內(nèi)部調(diào)用父組件傳入的函數(shù)(即this.props.onInputChange
,該函數(shù)用來重新更新父組件內(nèi)部的狀態(tài))
實現(xiàn)原理:
將父組件內(nèi)的屬性及方法(該方法是對父組件內(nèi)的狀態(tài)更新)傳給子組件,在子組件內(nèi)綁定相應(yīng)的事件束亏,在事件處理函數(shù)中調(diào)用父組件內(nèi)方法(以達到對父組件內(nèi)狀態(tài)更新的目的)铃在,當父組件內(nèi)狀態(tài)更新時會重新將相應(yīng)的屬性傳給子組件。
造成的原因:
在react.js中數(shù)據(jù)是自上而下單向流動的碍遍,故在子組件內(nèi)只能利用props屬性來來自父組件的值定铜,而在該實例中的大寫input
框和小寫input
框是屬于同級組件,無法利用props
屬性相互傳值怕敬,故只能在父組件內(nèi)共享數(shù)據(jù)揣炕,而在子組件內(nèi)利用事件處理函數(shù)來調(diào)用父組件內(nèi)對狀態(tài)的處理函數(shù)。
個人理解赖捌,僅供參考祝沸,如有錯誤,還望提出越庇!