开发者

React: triggering state change in child component

开发者 https://www.devze.com 2022-12-07 21:05 出处:网络
I have a parent that is clearing the fields of several input fields (a reusable child component). Parent:

I have a parent that is clearing the fields of several input fields (a reusable child component).

Parent:

const AdvancedSearch: FC<SearchProps> = memo(_props => {

// various other things

const resetFields = () => {
    setFields(data.initialFieldValues) // this replaces all text input with initial values of ''
    // trying to also clear the validation messages
}

return <React.Fragment>
    <TextField>
    <TextField>
    <TextField>
</React.Fragment>
}

Child:

const TextField: FC<TextFieldProps> = memo(props => {

  const [validationMessage, setValidationMessage] = useState(undefined as string | undefined) 

  let input = e.currentTarget.value

  const onTextChange = (e: React.FormEvent<HTMLInputElement>) => {
    props.foo = input
    const error = validateNumericInput(input)
    setValidationMessage(error)
  }

  return <InputText value={props.foo}
  placeholder={props.placeholder}
  maxLength={props.maxLength}
  onChange={onTextChange开发者_如何学Go}
  className={validationMessage ? `${classes.invalid}` : ''} />
}

The resetFields method in the parent successfully clears the input fields by replacing them with the initial values from props.foo but that obviously doesn't trigger the onChange event and I can't figure out how to reset the validationMessage via resetFields.

NB. the syntax could be wrong as I have truncated...

TIA

Gosh I can't remember what I've tried it feels like I've tried everything and getting very muddled haha.

I'm not sure whether I should be using const [validationMessage, setValidationMessage] = useState(undefined as string | undefined) in this child or something like this in the props:

export type TextFieldProps = {
    setValidationMessage?(validationMessage: string): string
}


Seems like a good use case for useEffect

const TextField: FC<TextFieldProps> = (props) => {
  const [validationMessage, setValidationMessage] = useState('');

  useEffect(() => {
    if (!props.foo) setValidationMessage('');
  }, [props.foo]);

  ...
}

This hook executes the callback function whenever one of the dependencies in the array changes.

You can execute whatever code you want when props.foo changes.

0

精彩评论

暂无评论...
验证码 换一张
取 消