React functional components

React components: class components and can be divided into functional components

1, there is no functional state component

2, functional components no life cycle (focus method involves the life cycle can only be set up in the class defined)

With hooks react may be provided by the state to do and methods in functional form

useState react object has a function that can be created by the state of the function, and the function return value is:

const [count,setCount] = useState(0); 
console.log(useState(0)) //[0, ƒ]

得到两个值count和setCount,分别为创建的state和操作state的方法,
名称是根据我们自己的需求命名的,由于该方法返回的是数组,因此我们直接用数组解构
的方式来接收返回值即可

** Note: ** When using setCount method, the method of directly modifying the value will count value for incoming argument.

export default () => {
    let [count, setCount] = useState(1)    //state部分
    const add = (arg) => { setCount(arg) } //操作状态的方法 }函数组建的三个组成结构
    return (<div>						   //return结构
        <p>{count}</p>
        <button onClick={() => add(count + 1)}>+</button>
    </div>)
}
//每次点击button,setCount都会设置count的值为当前值加1;

Formation is a function constituting the general structure, divided into three parts:

1, state portion; Method 2, the operating state; 3, return structure (as shown in the above code Notes)

No matter how complex a function of components should follow this deconstruction to create.

Function used in the formation of props:

props use similar class components used, the parent component needs to be exposed to the interface subassembly, the subassembly can be received, the received data sub-assembly method: directly to the subassembly as a parameter (props).

//父级组件传过去
export default () => {
    let [count, setCount] = useState(1)
    const add = (count) => { setCount(count) }
    return (<div>
        //类似类组件中的接口传递数据到子组件
        <Title count={count} />   
        <button onClick={() => add(count + 1)}>+</button>
    </div>)
}
//子组件接收
export default (props) => {
    return (
        <h1>{props.count}</h1>
    )
}

Then click button achieve effect a change in the state count value, the only method for packaging a good increase and decrease, and then passed over the interface to Ibutton components:

export default () => {
    let [count, setCount] = useState(1)
    const changeState = (count) => { setCount(count) }
    return (<div>
        <Title count={count} />
        <Ibutton onClick={() => changeState(count + 1)} name="+" />
        <Ibutton onClick={() => changeState(count - 1)} name="-" />
    </div>)
}
//Ibutton组件代码
export default (props) => {
    return <button onClick={props.onClick}>{props.name}</button>
}

Like this simply to complete the implementation of state worth a functional component changes.

Published 19 original articles · won praise 0 · Views 267

Guess you like

Origin blog.csdn.net/Joey_Tribiani/article/details/104468729