props
image.png
- 從子元素傳遞onCLick事件給父元素
// 父元素
export default class Father extends React.Component {
render() {
return (
<Child handleClickOrder={this.handleClickOrder.bind(this)} />
)
}
handleClickOrder(){
}
}
// 子元素
export default class Child extends React.Component {
render() {
return (
<div onClick={this.props.handleClickOrder}>
</div>
)
}
}
- 從子元素傳遞onCLick事件(帶參數(shù))給父元素
// 父元素
export default class Father extends React.Component {
render() {
return (
<Child handleClickOrder={this.handleClickOrder.bind(this)} />
)
}
handleClickOrder(Id){
console.log(Id);
}
}
// 子元素
export default class Child extends React.Component {
render() {
return (
<div onClick={()=>{this.props.handleClickOrder(this.props.data.id)}}>
</div>
)
}
}
如上所示,父元素獲取到子元素的Id髓考,注意,子元素的onClick
不能寫成onClick={this.props.handleClickOrder(this.props.data.id)}
,會造成重復渲染
state
ref
- 獲取dom元素
父組件例诀、子組件獲取dom元素
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
}
render() {
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
image.png
- 獲取自定義組件
父組件直接獲取自定義的子組件
import React from 'react'
import WWTextView from './WWTextView'
export default class NotFound extends React.Component {
render() {
console.log('render');
return (
<div>
<WWTextView
ref={(input)=>{this.textInput=input}}
/>
</div>
)
}
componentDidMount(){
this.textInput.focusTextInput();
}
}
自定義組件WWTextView如下
import React from 'react'
export default class WWTextView extends React.Component {
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
console.log('haha');
}
render() {
console.log('render');
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput.bind(this)}
/>
</div>
)
}
}
props與state區(qū)別
名稱 | props | state |
---|---|---|
使用場景 | 父組件傳值給子組件 | 表示組件內(nèi)部狀態(tài)荸哟,不限父組件橙数、子組件 |
重新渲染 | 父組件傳給子組件的props發(fā)生變化持钉,也會導致子組件的重新渲染 | state變化導致組件重新渲染 |
用途 | 用于放置初始化數(shù)據(jù),且一直不變的 | 用于放置那些組件變化而更新的數(shù)據(jù) |