
课程内容:今天学习的主要内容包括:react入门,学习编写react组件。
课程收获:
老师说,建议对组件要减少一些嵌套。因为在RN里面,层级少一些的话,会加快渲染的速度。
示例代码:
import React from "react";
class App extends React.Component {
render(): React.ReactNode {
let views = [];
views.push(1111)
views.push(2222)
return views;
}
}
export default App;
在React里面this.props.chridren会返回组件对象的所有属性,react提供了方法React.Children来处理this.props.chridren
示例代码:
class NotesList extends React.Component {
render(): React.ReactNode {
return (
{React.Children.map(this.props.children, (child) => {
return {child}
})}
)
}
}
然后在引用这个组件
class App extends React.Component {
render(): React.ReactNode {
let views = [];
views.push(1111)
views.push(2222)
views.push(
1
2
)
return views;
}
}
export default App;
这个时候页面就会把span给放到h1里面去显示了
我们在需要使用到组件的真实节点时可以用这个方法。
先定义一个测试的类
class Alert extends React.Component {
showAlert(msg: string) {
alert(`Debug:${msg}`)
}
render(): React.ReactNode {
return null
}
}
在父组件引用
class App extends React.Component {
setTextInputRef: React.Ref;
textInput: Alert | null | undefined;
constructor(props: {} | Readonly<{}>) {
super(props);
this.setTextInputRef = element => {
this.textInput = element;
};
}
onClick = () => {
this.textInput?.showAlert("111");
}
render(): React.ReactNode {
return <>
点我
>
}
}
export default App;
然后点击的话,可以看到有个弹窗出来
在上面的代码。APP组件的子节点有一个Alert组件,我们可以通过Ref来对这个组件内部的方法进行调用。
需要注意的是,因为refs获取的是真实Dom。所以我们必须要等到Dom渲染完成后进行获取,否则会报错。就用到了生命周期。
今天学习课程加练习一共用了40分钟,学习了两个React的方法,发现自己还有很多知识点没有涉及到,希望每天都能有这样的收获