[英]what to do when you have multiple repetitive components in react native
所以我有以下反應本機元素組件:
<CheckBox
containerStyle={[styles.checkBox, {borderColor: this.getCheckBoxColor(this.state.art)}]}
textStyle={[styles.text, {color: this.getCheckBoxColor(this.state.art)}]}
title='Art'
checkedColor={this.getCheckBoxColor(this.state.art)}
uncheckedColor={this.getCheckBoxColor(this.state.art)}
checkedIcon='paint-brush'
uncheckedIcon='paint-brush'
size={15}
checked={this.state.art}
onPress={() => this.setState({art: !this.state.art})}
/>
基本上,我的應用程序將顯示一系列這樣的復選框,詢問用戶他們喜歡談論的不同主題。 在這種情況下,此復選框詢問用戶是否喜歡談論藝術。 因此,每個主題將具有一個復選框和一個狀態值(在這種情況下,狀態值是this.state.art),狀態值可以為true或false,取決於是否選中了該復選框。 函數getCheckBoxColor接收狀態值並相應地設置復選框的顏色(如果狀態為true,則復選框變為白色,如果狀態為false,則復選框變為灰色)。 事實是,有14個不同的主題,我不想復制和粘貼此組件14次,而不必在每個主題中都更改主題。 我在考慮也許有一個可重用的復選框組件用作子組件,並向下傳遞它需要作為道具的特定主題數據(例如標題,選中和未選中的圖標以及狀態值),但是,由於復選框需要在按下狀態時更改狀態,我不確定如何完成此操作,因為React Native僅允許子組件通過將回調函數作為道具傳遞給子組件來更改父組件的狀態,但我不知道想在父組件中編寫14個不同的回調函數。 有沒有更好的辦法?
您可以在父組件中使用通用函數,例如handleCheckboxUpdate = (name) => this.setState({ [name]: !this.state[name] })
。
然后,子元素可以使用this.props.onCheckboxUpdate(this.props.title.toLowerCase())
進行調用。
如果子元素的標題屬性在父項狀態中並不總是與鍵匹配,則可以添加其他name
屬性。
這樣定義您的14個主題。
const topics = [{name: 'art', title: 'Art'}, ...]
定義一個通用方法來呈現您的復選框。
renderCheckbox(key, title) {
return (
<CheckBox
containerStyle={[styles.checkBox, {borderColor: this.getCheckBoxColor(this.state[key])}]}
textStyle={[styles.text, {color: this.getCheckBoxColor(this.state[key])}]}
title=title
checkedColor={this.getCheckBoxColor(this.state[key])}
uncheckedColor={this.getCheckBoxColor(this.state[key])}
checkedIcon='paint-brush'
uncheckedIcon='paint-brush'
size={15}
checked={this.state[key]}
onPress={() => this.setState({ [key]: !this.state[key] })}
/>
)
}
現在遍歷您的主題並呈現所有14個復選框。
renderAllTopics(topics) {
return(
{topics.map((row, index) => (
this.renderCheckbox(row.name, row.title)
))}
)
}
如果只想用於特定主題,則可以這樣渲染:
this.renderCheckbox(topicName, topicTitle)
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.