ReactJS component not rendering textarea with state variable

前端 未结 3 1967
无人共我
无人共我 2021-02-01 16:26

I am facing an intriguing bug in React.

I have this component:

\'use strict\';
import SummaryStore from \'../stores/SummaryStore\';
import React from \'rea         


        
相关标签:
3条回答
  • 2021-02-01 17:07

    Check this link from react docs: React Textarea Value

    Basically for textArea react does not supports text enclosed within and you rather need to specify that as value or defaultValue.

    The right way thus is

    <textarea name="description" value="This is a description." />
    

    or

    <textarea name="description" defaultValue="This is a description." />
    

    The difference with value and defaultValue is that specifying defaultValue leaves the component uncontrolled:

    With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value.

    ...while specifying value instructs React to control the component, meaning you need to update value property to make sure that change is reflected in the component:

    Since the value attribute is set on our form element, the displayed value will always be this.state.value, making the React state the source of truth.

    To get a clear idea of difference between value / default value check this: Fiddle for value Default Value Distinction Console will always show new value but component will not.

    0 讨论(0)
  • 2021-02-01 17:16

    Actually that is exactly what is wrong. From the docs:

    If you want to initialize the component with a non-empty value, you can supply a defaultValue prop.

    0 讨论(0)
  • 2021-02-01 17:23

    I had the same problem. I solved it by using controlled component, e.g.

    state.value = this.props.value 
    <textarea value={this.state.value} onchange={handler} />
    

    It works fine to control the input part. However, I had another issue, I need to init/change the state.value to props.value whenever there is a re-render.

    I used the lift-cycle methods and it works perfect fine.

    componentWillReceiveProps: function(){
        this.setState({
            value: this.props.value
        }) }
    

    hope this helps.

    0 讨论(0)
提交回复
热议问题