React input defaultValue doesn't update with state

后端 未结 5 1621
孤街浪徒
孤街浪徒 2020-11-28 05:27

I\'m trying to create a simple form with react, but facing difficulty having the data properly bind to the defaultValue of the form.

The behavior I\'m looking for is

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 06:18

    Maybe not the best solution, but I'd make a component like below so I can reuse it everywhere in my code. I wish it was already in react by default.

    
    

    The component may look like:

    window.MagicInput = React.createClass
    
      onChange: (e) ->
        state = @props.binding[0].state
        changeByArray state, @path(), e.target.value
        @props.binding[0].setState state
    
      path: ->
        @props.binding[1].split('.')
      getValue: ->
        value = @props.binding[0].state
        path = @path()
        i = 0
        while i < path.length
          value = value[path[i]]
          i++
        value
    
      render: ->
        type = if @props.type then @props.type else 'input'
        parent_state = @props.binding[0]
        ``
    

    Where change by array is a function accessing hash by a path expressed by an array

    changeByArray = (hash, array, newValue, idx) ->
      idx = if _.isUndefined(idx) then 0 else idx
      if idx == array.length - 1
        hash[array[idx]] = newValue
      else
        changeByArray hash[array[idx]], array, newValue, ++idx 
    

提交回复
热议问题