react中如何對自己的組件使用setFieldsValue
react對自己的組件使用setFieldsValue
setFieldsValue的用法
setFieldsValue是antd form的一個api,其作用是對指定的已使用from包裹的表單進行value設(shè)置。那么所以它的功能也很簡單,那就是給指定的input設(shè)置value。
如下所示:
import React from "react";
import { Form, Input } from 'antd';
class TestForm extends React.Component {
? componentDidMount(){
? ? const { setFieldsValue } = this.props.form;
? ? // 這里就能實現(xiàn)指定表單設(shè)置value
?? ?setTimeout(()=>{
?? ??? ?setFieldsValue({"username": "Tom"})
?? ?},5000)
? }
? render() {
? ? const { getFieldDecorator } = this.props.form;
? ? return (
? ? ? <Form >
? ? ? ? <Form.Item>
? ? ? ? ? {getFieldDecorator('username', {})(<Input />)}
? ? ? ? </Form.Item>
? ? ? </Form>
? ? );
? }
}
export default Form.create()(TestForm)問題
那么假如把
{getFieldDecorator('username', {})(<Input />)}換成
{getFieldDecorator('username', {})(<TestInput />)}setFieldsValue 設(shè)置的value去哪了?相信聰明的你一眼就看透了,自然是在TestInput上面。假如TestInput是我們自定義的組件,那么我們則可以在props中找value這個屬性,那么假如我們的Input是自定義的input組件,我們可以這么寫
import React from "react";
import { Input } from 'antd';
class TestInput extends React.Component {
?? ?state = {
?? ??? ?value: ""
?? ?}
?? ?
?? ?componentWillReceiveProps(nextProps){
?? ??? ?if(nextProps.value){
?? ??? ??? ?this.setState({
?? ??? ??? ??? ?value: nextProps.value
?? ??? ??? ?})
?? ??? ?}
?? ?}
?? ?
?? ?render() {
?? ? ? ?return (
?? ? ? ? ?<div >
?? ? ? ? ? ? ?<Input value={this.state.value}/>
?? ? ? ? ?</div>
?? ? ? ?);
? ?? ?}
}
export default TestInput這樣,我們就能使用setFieldsValue設(shè)置自定義的組件了
使用Hooks使用setFieldsValue設(shè)置初始值無效

錯誤:
useEffect(() => {
if (formConfigListValues.length === 0) {
form.resetFields();
if (statusId) {
form.setFieldsValue({flowStatus: 1});
}
}
}, [formConfigListValues, statusId]);
因為formConfigListValues在每次操作完表單時候要走一遍,但是導(dǎo)致了,審批狀態(tài)一直不會變(也就是操作審核狀態(tài)失效);
正確:
useEffect(() => {
if (formConfigListValues.length === 0) {
form.resetFields();
}
}, [formConfigListValues]);
useEffect(() => {
if (statusId) {
form.setFieldsValue({flowStatus: 1});
}
}, [statusId]);
在hooks中使用setFieldsValue,還要注意寫代碼的順序和層級結(jié)構(gòu)(如:新加的setFieldsValue到底放在里邊還是外邊,放到外邊的話是否要注意,要放在resetFields所在useEffect的下邊)。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
React?Hooks之useDeferredValue鉤子用法示例詳解
useDeferredValue鉤子的主要目的是在React的并發(fā)模式中提供更流暢的用戶體驗,特別是在有高優(yōu)先級和低優(yōu)先級更新的情況下,本文主要講解一些常見的使用場景及其示例2023-09-09
React.InputHTMLAttributes實踐和注意事項
文章討論了如何在封裝組件中使用React.InputHTMLAttributes,以及如何通過 {...inputProps} 動態(tài)傳遞屬性,最后,文章總結(jié)了使用React.InputHTMLAttributes的最佳實踐和注意事項,感興趣的朋友一起看看吧2024-11-11

