首页 > 解决方案 > Enhancing/manipulating react children props

问题描述

I was hoping to abstract away the binding of event listeners on children components. Or allow a component to alter props of children.

I'm wanting to express the components in JSX like

<DocumentScreen name="Type">
  <DocumentInput value="L" name="(=learner)" icon="lerners.svg" />
  <DocumentInput value="P" name="(=probationary)" icon="probationary.svg" />
  <DocumentInput value="Full" icon="full.svg" />
</DocumentScreen>

Which is an enhanced radio or checkbox grouping.

Now I want to enhance the inputs to automagically notify the parent component of changes to store state.

I was hoping this would be possible

{React.Children.toArray(this.props.children).map((Child => (<Child onClick={() => console.log("yea!")} />)))}

Or more simply

{this.props.children.map((Child => (<Child onClick={() => console.log("yea!")} />)))}

But I get a typescript error

JSX element type 'Child' does not have any construct or call signatures

Using

"react": "^16.8.6",
"typescript": "^3.5.2"

Is this possible or is there another way to achieve this?

标签: javascriptreactjstypescript

解决方案


You can use cloneElement

https://reactjs.org/docs/react-api.html#cloneelement

render() {
        return (
          <div>
          {React.Children.map(this.props.children, child => {
            return React.cloneElement(child, {
                onClick : () => console.log("yea!")
            })   
         })}
         </div>
       ) 
}

推荐阅读