[英]use ref for parent elements in dynamic blocks React
你能告訴我如何正確地在父塊上做 ref
我只知道在virtualDom中使用選擇器是錯誤的,我需要使用refs
如何使引用替換方法 addTag 和 editTags 中的選擇器?
class Home extends Component { editTags = (e) => { e.target.closest('.card-list__item--tags').classList.add('active'); } addTag = (e) => { let tagFieldValue = e.target.closest('.card-list__item_edit').querySelector('input'); let indexItem = e.target.closest('.card-list__item').id; let cardList = this.props.cards; cardList[indexItem].tags = cardList[indexItem].tags + ', ' + tagFieldValue.value; this.props.onEditTags(cardList); tagFieldValue.value = ''; e.target.closest('.card-list__item--tags').classList.remove('active'); } render(){ let cardList = this.props.cards; return( <div className={'card-list'}> { cardList.length && cardList.map((card, index) => <div id={index} className={'card-list__item'}> <div className={'card-list__item_row card-list__item--tags'}> <div className={'tags-wrap'} onDoubleClick={this.editTags}> { card.tags.split(', ').map((tag) => <span>{tag}</span> ) } </div> <div className={'card-list__item_edit'}> <input id={index} type="text" placeholder={'Add tags'}/> <button onClick={this.addTag}>Add Tag</button> </div> </div> </div> ) } </div> ) } } export default Home;
假設您使用的是 React 16.10.0 及更高版本,您可以使用如下引用:
class Home extends React.Component {
constructor(props) {
super(props)
this.cardListRef = React.createRef();
}
addTag = (e) => {
const cardListRefNode = this.cardListRef.current;
console.log(cardListRefNode); // card-list node will be available here
let tagFieldValue = e.target.closest('.card-list__item_edit').querySelector('input');
let indexItem = e.target.closest('.card-list__item').id;
let cardList = this.props.cards;
cardList[indexItem].tags = cardList[indexItem].tags + ', ' + tagFieldValue.value;
this.props.onEditTags(cardList);
tagFieldValue.value = '';
e.target.closest('.card-list__item--tags').classList.remove('active');
}
render(){
let cardList = this.props.cards;
return(
<div className={'card-list'} ref={this.cardListRef}>
{
cardList.length && cardList.map((card, index) =>
<div id={index} className={'card-list__item'}>
<div className={'card-list__item_row card-list__item--tags'}>
<div className={'tags-wrap'} onDoubleClick={this.editTags}>
{
card.tags.split(', ').map((tag) =>
<span>{tag}</span>
)
}
</div>
<div className={'card-list__item_edit'}>
<input id={index} type="text" placeholder={'Add tags'}/>
<button onClick={this.addTag}>Add Tag</button>
</div>
</div>
</div>
)
}
</div>
)
}
但正如我所見,您正在使用選擇器從輸入中獲取值、清除輸入和切換類。 在 React 中創建 Refs 是為了另一個目的(https://reactjs.org/docs/refs-and-the-dom.html#when-to-use-refs )。
在您的情況下,最好將組件的 state 用於此類任務。 您可以通過 onChange 事件從輸入中獲取值,然后您可以將這些值存儲在組件的 state 中。 此外,最好將“'card-list__item'”移動到單獨的組件並根據其 state 在其中切換活動的 class 。 你可以在這里找到更多關於如何在 React 中使用 forms 的示例: https://reactjs.org/docs/forms.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.