Data binding in React

前端 未结 12 775
心在旅途
心在旅途 2021-01-30 19:49

What I want to do is when I type some text in an input field, it should appear in another place realtime.

Below is my input;



        
12条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 20:51

    This could be achieved with a hook. However, I would not recommend it, as it strictly couples state and layout.

    November 2019 Data Bind with Hooks

    const useInput = (placeholder, initial) => {
        const [value, setVal] = useState(initial)
        const onChange = (e) => setVal(e.target.value)
        const element = 
        return {element, value}
    }
    

    Use it in any functional component

    const BensPlayGround = () => {
        const name = useInput("Enter name here")
        return (
            <>
                {name.element}
                

    Hello {name.value}

    ) }

    Basic version - bind value and onChange

    const useDataBind = () => {
        const [value, setVal] = useState("")
        const onChange = (e) => setVal(e.target.value)
        return {value, onChange}
    }
    
    const Demo = (props) => {
        const nameProps = useDataBind()
        return (
            <>
                
                

    Hello {nameProps.value}

    ) }

提交回复
热议问题