问题是我想使用Redux,并基于edit toggle(product.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
),
}
}
我希望toggle往返于Edit and View模式对您有用。
现在,如果您的问题是:
如何修改产品详细信息(标题,说明等), 特定产品处于编辑模式?
这是您的操作方式:
form
中,使用uncontrolled而不是defaultValue
将其设置为value
input
的submit
按钮(它将使您可以通过在任意字段中单击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 ?
进行比较,而不是===
,==
您可以尝试在inputfield的readonly属性中使用布尔值