知识点
需要准备知识
- 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.方法 ()
第二种是提供闭包函数;注意子组件参数需要写成闭包类型;可以直接调用;
2365

被折叠的 条评论
为什么被折叠?



