如何让输入字段在toggle时可以编辑,并基于toggle的redux?

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

问题是我想使用 重编 并基于 编辑切换 (product.editable)应该检查文本是否可编辑。

但一切都很顺利,直到我想编辑输入字段内的值。

我需要有人能帮助我找到正确的方向。我知道JSON是不能直接修改的,但是我怎么才能改变当前的值,然后让它在输入字段里面可以编辑。请记住,我使用的是哑巴组件。

组件。

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
1个回答
1
投票

我希望 拨动 往返 编辑和查看 模式为你工作。

现在如果你的问题是

如何在某一商品进入编辑模式后修改商品详情(标题、描述等)?

以下是你的操作方法。

  • 把你的输入字段包装成 form,使其 不受控制 借用 defaultValue 而不是 value
  • 放置 inputsubmit (它将让你通过点击 进入 在任何领域。隐蔽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 而不是 index 如有可能,如产品ID
  • 您可以使用 editable: !product.editable 中,而不是 editable: product.editable == true ? false : true
  • 使用 id 如果可能的话,在你的减速器中找到要更新的产品,而不是用 index : (products.map((product, i) => i == action.index ?)
  • 使用 === 来比 ==, 更多

0
投票

你可以尝试使用输入字段的readonly属性中的布尔值。

<input readOnly={product.editable} />
© www.soinside.com 2019 - 2024. All rights reserved.