React核心知识点
介绍
react是最近很是流行的框架,相对于vue框架,对js、es6以及以上的版本的语法要求会更高。核心是把设计好的UI划分成组件层级。
JSX的使用
js是JavaScript的语法扩展。在编译的时候JSX表达式会被转为不同js对象,所以把jsx表达式嵌入if语句或者for 也都是没有问题的.
# 基本表达式
const element = <h1>Hello World!</h1>
# 嵌入函数中,编译成为函数组件
function geGretting(){
return <h1>Hello Gretting </h1>;
}
# JSX使用特定属性
const element = <img src={img.url} />
# jsx 表示对象
const el = (
<h1 className = "greeting">
Hello World!
</h1>
)
React.createElement(
'h1',
{classNmae:'greeting'},
'Hello World!'
)
函数组件和class组件
# 函数组件
function Welcome (){
return <h1>Hello World!</h1>
}
# class组件
class Welcome extends React.Component{
render(){
return (
<h1>Hello World</h1>
);
}
}
父子组件之间通信
父组件向子组件传值
function Child(props){
return <div>{props.name}</div>
}
class Parent extends React.Component{
render(){
return(
<Child name="www1"></Child>;
<Child name="www2"></Child>;
)
}
}
子组件向父组件传值
class Child extends React.Component{
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this); //重要操作
}
function handleChange(e){
this.props.handleParent(e.target.value)
}
render(){
return (
<input onChange={this.handleChange} ></input>
)
}
}
class Parent extends React.Component{
constructor(props) {
super(props);
this.onHandle = this.onHandle.bind(this); //重要操作
}
function onHandle(value){
console.log("最终获取到从子组件传进的参数")
}
render(){
return(
<Child handleParent={this.onHandle}></Child>;
)
}
}
Hook特性
Hook是react新增的一个属性,在不编写class组件的时候使用其他React的特性。
- 特性一:count属性相当于 this.state.count
function Example(){
const [count,setCount] = useState(0) //初始化count为0
return (
<div >{count}</div>
<button onClick ={()=>{setCount(count+1)}} ></button>
)
}
#等价与如下
class Example extends React.Component{
constructor(props){
super(props);
state={ count:0};
}
render(){
return (
<div >{count}</div>
<button onClick ={()=>{this.setState({count:count+1)}) } ></button>
)
}
}
注意点:
- props的内容不可更改
- 组件名首字母大写
- 在return的内容最外层必须要有一个div大标签,或者用 <React.Fragment></React.Fragment>包括在最外层