簡體   English   中英

反應功能組件-當組件返回元素數組時,如何將引用傳遞回父級?

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

我有一個React組件,其中包括一個無狀態功能組件。 內部組件在值數組上運行Lodash map ,以返回p標簽數組。

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'));

我的Application組件需要對這些DOM元素的引用,因此我想將每個p標簽的ref返回給父組件。 誰能建議最好的方法嗎? 我發現的所有示例都假定子組件是單個元素。

Codepen示例

現在在React 16.3中,您可以使用React.createRef()創建引用,並將它們從父組件傳遞給子組件。 是文檔。 因此,您可以映射父組件中的項目,並使用ref屬性對其進行擴展。

希望這對您有用。

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'));

對於初學者,您可能想在這里閱讀-

然后,如果您掌握了react中引用的概念,那么我已經完成了對Codepen筆對JS文件所做的一些非常簡單的更改(請參見下文)。

我正在粘貼新筆,並在此處添加所需的規格-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'));

查看代碼,如果您有任何疑問,請告訴我:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM