知識點
需要準備知識
- typescript
- React
單項數據流
- React是單向數據流,數據主要從父節點傳遞到子節點(通過props),如果頂層(父級)的某個props改變了,React會重渲染所有的子節點。
Props
props是隻讀的,不可以使用this.props直接修改props,props是用於整個組件樹中傳遞數據和配置。在當前組件訪問props,使用this.props。
方法傳遞
由於React是單項數據流;所以如果子組件需要調用父組件的方法,只能讓父組件將方法傳遞子組件上,有子組件通過this.props.方法調用;或者通過閉包在方法上調用;
案例
父組件
import * as React from 'react';
import Child from './child'
interface IParentProps{
name : string
}
class Parent extends React.Component<IParentProps,{date:Date,text:string}>{
static defaultProps = {
name: "stranger",
};
constructor(props) {
super(props);
this.state = { date: new Date(), text: '123' };
}
// 普通方法
private renderText = (str:string) => {
const {name} = this.props;
console.log(this)
this.setState({
text: name || str
})
}
// 閉包方法
private handelView = (viewId: string) => () => {
const { name} = this.props
setTimeout(function(){
console.log(name);
},2000)
}
render() {
const { name } = this.props;
return (
<div>
<h1>Hello, world!{name}</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
<Child
hookTitle={this.state.text}
onHook={this.renderText}
handelView={this.handelView}
></Child>
</div>
);
}
}
export default Parent;
子組件
import * as React from 'react';
/**
* 注意下面handelView是閉包函數的寫法,可以直接在render中調用,不需要通過this.props.方法調用
*/
interface IParentProps{
hookTitle: string
onHook: (display: string) => void
handelView:(viewId:string) => () => void;
}
class Child extends React.Component<IParentProps> {
constructor(props: IParentProps) {
super(props)
this.state = {
text: '123'
}
this.handelClick = this.handelClick.bind(this)
}
private handelClick(){
let i = 0;
console.log(this);
this.props.onHook((new Date().toUTCString()));
}
render() {
const { hookTitle, onHook, handelView} = this.props;
return (
<div>
<span>{hookTitle}</span>
<button onClick={this.handelClick}>調用onHook函數</button>
{/*不能直接調用, 需要函數執行*/}
{/* <button onClick={onHook('123')}>調用父組件閉包函數</button> */}
{/* 直接調用閉包函數 */}
<button onClick={handelView('調用handleView')} > 調用父組件閉包函數</button>
</div>
)
}
}
export default Child;
總結
以上的案例就是父組件給子組件傳值;同時子組件調用父組件的方法;方法調用分爲2種;
一種是通過普通的函數,子組件調用時候通過this.props.方法 ()
第二種是提供閉包函數;注意子組件參數需要寫成閉包類型;可以直接調用;