前言: 在复杂的组件中,我们最好把组件拆分为UI组件和容器组件
以方便我们的管理和维护
1、拆解前的组件
import React, {Component} from 'react'
class Test extends Component{
constructor(props){
super(props)
this.state = {
list: ['a', 'b', 'c']
}
}
render() {
return (
<ul>
{this.state.list.map( (item, index) => (
<li
key={item}
onMouseMove={this.showItem.bind(this)}
onClick={this.showIndex.bind(this, index)}
>{item}</li>)
)}
</ul>
)
}
showItem(e){
console.log(e.target.innerHTML)
}
showIndex(index){
console.log(index)
}
}
export default Test
2、创建 [组件UI.js] 来存放
如果一个组件只有 render 函数,我们可以把这个组件变成无状态组件,这样性能会大大提高
- 一般 UI 组件,都可以变成无状态组件
- 下面这个就是无状态组件
import React, {Component} from 'react'
const TestUI = (props) => {
return (
)
}
export default TestUI
并在Test.js 中引入
import TestUI from './TestUI'
// 在render中引入
render() {
return (
<TestUI />
)
}
3、state里值的传递
-
传递 list 来渲染 li
-
Test.js
// 在constructor中有值list
this.state = {
list: ['a', 'b', 'c']
}
// 在子组件TestUI中通过自定义属性传过去
render() {
return (
<TestUI
list={this.state.list}
/>
)
}
TestUI.js
import React, {Component} from 'react'
const TestUI = (props) => {
//即可以用 props 来接收且使用
return (
<ul>
{props.list.map( (item, index) => (
<li key={item}>{item}</li>)
)}
</ul>
)
}
export default TestUI
4、不带参数的函数的传递
- 每次鼠标在 li 上移动,都会打印出对应的 li 的 html
Test.js
constructor(props){
super(props)
this.state = {
list: ['a', 'b', 'c']
}
this.showItem = this.showItem.bind(this) // 已经在此进行了this指向的改变
}
showItem(e){
console.log(e.target.innerHTML)
}
// 在子组件TestUI中通过自定义属性传过去
render() {
return (
<TestUI
list={this.state.list}
showItem={this.showItem}
/>
)
}
TestUI.js
import React, {Component} from 'react'
const TestUI = (props) => {
//即可以用 props 来接收且使用
return (
<ul>
{props.list.map( (item, index) => (
<li
key={item}
onMouseMove={props.showItem}
>{item}</li>)
)}
</ul>
)
}
export default TestUI
5、带参数的函数的传递
- 每次点击 li,都会打印出对应的 li 的下标
Test.js
constructor(props){
super(props)
this.state = {
list: ['a', 'b', 'c']
}
this.showIndex = this.showIndex.bind(this) // 已经在此进行了this指向的改变
}
showIndex(index){
console.log(index)
}
// 在子组件TestUI中通过自定义属性传过去
render() {
return (
<TestUI
list={this.state.list}
showIndex={this.showIndex}
/>
)
}
TestUI.js
import React, {Component} from 'react'
const TestUI = (props) => {
//即可以用 props 来接收且使用
return (
<ul>
{props.list.map( (item, index) => (
<li
key={item}
onClick={ () => {props.showIndex(index)} }
>{item}</li>)
)}
</ul>
)
}
export default TestUI