简体   繁体   中英

React functional component - how do I pass refs back to parent when component returns an array of elements?

I have a React component that includes a stateless functional component. The inner component runs Lodash map on an array of values to return an array of p tags.

class Application extends React.Component {

  items = [
    'first',
    'second',
    'third',
  ];

  render() {
    return <div>
            <Paragraphs items={ this.items } />
        </div>;
  }

}

const renderItem = ( item, index ) => {
  return (
    <p key={ index }>{ item }</p>
  );
};

const Paragraphs = ( { items } ) => _.map( items, renderItem );

ReactDOM.render(<Application />, document.getElementById('root'));

My Application component needs references to these DOM elements, so I'd like to pass back a ref for each of the p tags back to the parent component. Can anyone suggest the best way to do this? All the examples I've found assume the child component is a single element.

Codepen example

Now in React 16.3 you can create refs with React.createRef() and pass them from parent component to child. Here is the docs. So you can map items in the parent component and extend them with ref property.

I hope this will work for you.

class Application extends React.Component {

    items = [
        'first',
        'second',
        'third',
    ].map(item => ({ item, ref: React.createRef() }))

    // you can access refs here: this.items[0].ref
    render() {
        return <div>
            <Paragraphs items={this.items} />
        </div>;
    }
}
const renderItem = (item, index) => {
    return (
        <p key={index} ref={item.ref} > {item.item} </p>
    );
};
const Paragraphs = ({ items }) => _.map(items, renderItem);
ReactDOM.render(<Application />, document.getElementById('root'));

for starters, you may want to read in here -

And then, if you have grasped the concept of references in react, I have done, some very simple changes( see below ) to the JS file from your codepen's pen.

I am pasting the new pen, with needed specs here - https://codepen.io/anon/pen/wjKvvw

class Application extends React.Component {

  items = [
    'first',
    'second',
    'third',
  ];
    item_refs = this.items.map(a=>{}) // making an empty list for references
    item_referer = (ele, ind) => { // a callback function to be called in the children where references are to be made
        this.item_refs[ind] = ele;
        console.log("Referring to", this.items[ind], ele) // a simple logging to show the referencing is done. To see open the console.
    }
    // passing the item_referer function as the prop (itemReferer) to children
  render() {
    return <div>
            <Paragraphs items={ this.items } itemReferer={ this.item_referer }/>
        </div>;
  }

}

const renderItem = ( item, index, referToMe ) => {
    // referToMe is the callback function to be called while referencing
  return (
    <p key={ index } ref={(el)=>referToMe(el, index)} >{ item }</p>
  );
};
// get the itemReferer prop passed to Paragraphs component and use it
// render the children.
const Paragraphs = ( { items, itemReferer } ) => items.map((item, index )=>{
    return renderItem(item, index, itemReferer) // passing to refer to the individual item
})

ReactDOM.render(<Application />, document.getElementById('root'));

Go through the code, if you have any questions, let me know :)

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