react组件
sonder 超大杯

react

  • react是facebook出的的针对view视图层的库。

    在使用react开发时,可以使用很多第三方插件。

jsx

  • 直接使用html标签

组件定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!--函数定义-->
<div id='app'></div>
function App(){
return (<h2>...</h2>)
}
ReactDOM.render(<App />,document.getElementById('app));
<!--ES6 class定义-->
const { Component } = React;
class App extends Component{
constructor(props){
super(props)
}
render(){
return (<h2>...</h2>)
}
}
ReactDOM.render(<App />,document.getElementById('app));

传值

  • 通过父组件传值给子组件->props
  • 子组件给父组件传值使用方法调用
1
2
3
4
5
6
7
8
9
10
11
12
<div id ='app'></div>
function Nav(props){
// const { name } = props 这里不加this 在class里定义的组件,传参需要加this
return (<h2> { props.name }</h2>)
}
function App(){
return (
<Nav name={123}/>
)
}

ReactDOM.render(<App />,document.getElementById('app'))
  • 子组件给父组件传值使用方法调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<div id='app'></div>
<script type='text/babel'>
const { Component } = React
class Child extends Component{
constructor(props){
super(props)
}

render(){
return (
<div>
<h2>这里是子组件</h2>
<button onClick={()=>this.props.toParent(event)}>点击</button>
</div>
)
}
}
class App extends Component {
onClickHandle(e){
console.log(e.target)//这里打印的是事件源,当参数为event时,才会打印事件源
}
render(){
return (
<div>
<Child toParent={this.onClickHandle.bind(this)}/>
</div>
)
}
}
ReactDOM.render(<App />,document.getElementById('app'))
</script>

== 当子组件是通过函数来定义的,那么想要获得事件源时,第一个括号要加参数e

1
2
3
4
5
function Child(){
return (
<button onClick={(e)=>props.toParent(e)}>点击</button>
)
}

函数组件和类组件的区别

  1. 函数定义的组件不会被实例化,整体渲染性能得到提升
  2. 函数定义的组件不能访问this对象
  3. 函数定义的组件无法访问生命周期的方法
  4. 函数定义的无状态组件只能访问输入的props,无副作用
  • 何时该使用函数式组件

    函数式组件相比类组件,拥有更好的性能和更简单的职责,十分适合分割原本庞大的组件,未来 React 也会对函数式组件进行一系列的优化,譬如无意义检查和内存分配领域相关的优化。所以只有有可能,尽量使用函数式组件。

ps: forEach只循环没有返回值。
map循环之后,会生成新的数组对象,生成的数组内容为每一次的返回值。

  • 本文标题:react组件
  • 本文作者:sonder
  • 创建时间:2019-07-29 09:29:09
  • 本文链接:https://sonderss.github.io/2019/07/29/react组件/
 评论