如何使输入字段在基于切换的redux切换时可编辑?

问题描述 投票:1回答:2

问题是我想使用Redux,并基于edit toggleproduct.editable),应检查文本是否可编辑。

但是一切顺利,直到达到我要编辑输入字段内的值为止。

我需要一个可以帮助我朝正确方向发展的人。我知道无法直接修改JSON,但是如何更改当前值,然后使其在输入字段中可编辑。请记住,我在使用哑巴组件。

Component:

let getProductList = productList.map((product, i) => {
  return (
    <div key={i}>   
      {product.editable ?   
        <div>
          <input name="title" ref={(input) => title = input} value={product.title}/>
          <input name="description" ref={(input) => description = input} value={product.description}/>
        </div>
      : 
        <div>
          <div>{product.title}</div>
          <div>{product.description}</div>
      </div>}
      <ProductButtons productId={product._id} index={i}/>
    </div>
  ) 
});

export const ProductButtons = ({ productId, index}) => {
  const dispatch = useDispatch();
  return (
    <div>
      <button onClick={() => dispatch(deleteItem(productId, index))}>Delete</button>
      <button onClick={() => dispatch(editItem(productId, index))}>Edit</button>
      <button onClick={() => dispatch(addItem(productId))}>Add</button>
    </div>
  )
}

Reducer:

case types.UPDATE_PRODUCT: {
  console.log('update')
  return {
    ...state,
    products: state.products.map((product, i) =>
      i == action.index
        ? {
            ...product,
            editable: product.editable == true ? false : true,
          }
        : product
    ),
  }
}
reactjs redux reducers
2个回答
1
投票

我希望toggle往返于Edit and View模式对您有用。

现在,如果您的问题是:

如何修改产品详细信息(标题,说明等), 特定产品处于编辑模式?

这是您的操作方式:

  • 将输入字段包裹在form中,使用uncontrolled而不是defaultValue将其设置为value
  • 放置一个类型为inputsubmit按钮(它将使您可以通过在任意字段中单击ENTER来提交表单,如果不想显示,请使用CSS进行隐藏)它):
<form onSubmit={this.handleSubmit}>
  <input
    name="title"
    ref={this.title}
    defaultValue={product.title}
    // value={product.title}
  />
  <input
    name="description"
    ref={this.description}
    defaultValue={product.description}
    // value={product.description}
  />
  <input
    type="submit"
    value="submit"
    className="display-none"
    style={{ display: 'none' }}
  />
</form>

handleSubmit功能:

handleSubmit = (e) => {
  e.preventDefault()
  e.stopPropagation()

  // you can use event to read form field values
  console.debug(e.target.title.value)
  console.debug(e.target.description.value)

  // or use the element Ref you created 
  console.debug(this.title.current.value)
  console.debug(this.description.current.value)

  // Here, you can make API call or dispatch action to your redux to update the data
}

其他几点:

  • [如果可能,请为key提供一些其他值,而不是key,例如产品编号
  • 您可以在减速器中使用index代替editable: !product.editable
  • 如果可能,请使用editable: product.editable == true ? false : true查找要在减速器中而不是id更新的产品:([index
  • 使用products.map((product, i) => i == action.index ?进行比较,而不是=====

0
投票

您可以尝试在inputfield的readonly属性中使用布尔值

more on this
© www.soinside.com 2019 - 2024. All rights reserved.