[英]How to dynamically add/delete view in react native?
您不需要自己操作視圖,您需要以可以迭代的形狀管理數據結構並呈現您想要的正確組件。
為了處理從數組中查找一個項目並將其刪除,我建議您為每個數組項目設置一個 ID,因此這意味着您需要將它們轉換為對象數組,並且每個對象都應該有一個id
鍵如下所示:
const myData = [
{ id: 1, val: 'some value' },
{ id: 2, val: 'some other value' },
// more ...
]
通過這樣做,您的 id 成為按 id 查找項目、按 id 過濾項目並執行您想要的任何結果的關鍵,並通過在您的狀態中設置結果對象數組,您的組件的return
部分將使用狀態,因為在您對其進行任何操作后,狀態總是會更新,然后您會看到結果正在自動更新!
如何在 react/react-native 中動態添加/刪除表單首先創建一個狀態數組來代表你的表單結構,現在它可以獲取你的任何 API,或者你可以手動創建它
this.state = {
array: [{
studentName: 'John doe',
uid: 1
}]
}
循環相同的狀態數組
{
array.map((item, index) => {
return (
<View style={{ margin: 5, padding: 10, }}>
<TextInput placeholder='Student name'
value={item.studentName}
style={{ borderRadius: 4, borderWidth: 1, borderColor: '#212121', padding: 8 }}
onChangeText={text => {
this.setState({ array: array.map((c, innerIndex) => innerIndex === index ? { ...c, studentName: text } : c) })
}} />
<TextInput placeholder='Student UID'
value={item.uid}
style={{ borderRadius: 4, borderWidth: 1, borderColor: '#212121', padding: 8, marginTop: 5 }}
onChangeText={text => {
this.setState({ array: array.map((c, innerIndex) => innerIndex === index ? { ...c, uid: text } : c) })
}} />
<Text style={{
alignSelf: 'flex-start', borderRadius: 4,
padding: 3, marginTop: 5, backgroundColor: 'red', color: 'white'
}} onPress={() => {
const filterList = array.filter((item, inner) => inner != index)
this.setState({ array: filterList })
}}>
Remove
</Text>
</View>
)
})
}
當您想再添加一個字段時,請創建一個處理程序,該處理程序只會將一個空對象添加到您的狀態數組,因為您已經循環了狀態數組,因此當狀態數組更改時,您的表單會更改
<Text style={{ padding: 16, textAlign: 'center', backgroundColor: 'black', color: 'white' }} onPress={() => {
this.setState({
array: [...array, {
studentName: '',
uid: ''
}]
})
}}>
Add
</Text>
完整的 App.js 代碼可在此處獲得
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.