简体   繁体   中英

React JS with redux-form with custom component

Found on redux from website the following example:

render() {
  return (
    <div>
      <Field name="myField" component={props =>
        <MyStrangeInput 
          currentValue={{val: props.value}}
          thingsChanged={param => props.onChange(param.val)}/>
      }/>
    </div>
  );
}

I understand that we pass MyStangeInput 2 arguments to the component, currentValue and thingsChanged.

currentValue been used and "value" and thingsChanged used as a method for "onChange"

I would love the get explanation regarding the following syntax:

{{ val: props.value}} - is it passing an object?

and

{param => props.onChange(param.val)} is it creating "param" arrow function?

it's a little bit confusing

currentValue={{val: props.value}} is creating an object with a key val and passing it to the MyStrangeInput component as the currentValue prop. The outer curly brackets mark the property value and the inner curly brackets define the object`. It would be also possible to create the object in the render method and just use it in the JSX context:

props => {
        const currentVal = { val: props.value};
        return <MyStrangeInput 
          currentValue={currentVal}
          thingsChanged={param => props.onChange(param.val)} />;
}

{param => props.onChange(param.val)} indeed creates an arrow function with param as the first and only parameter. It is a shorthand notation for

{(param) => {
  return props.onChange(param.val);
}}

Actually there are two syntax shortcuts used here. First you can omit the brackets around the parameter list if there is only one parameter ( param instead of (param) ) and second you can omit the curly brackets around the function body if you want to directly return the value of the only statement of the body ( props.onChange(param.val); instead of { return props.onChange(param.val); } )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM