の違いを私はカップルのクラスを開発していますネイティブ反応し、これがアップします:リアクトネイティブ、コンストラクタとcomponentWillReceiveProps
class Foo extends Component {
constructor(props) {
super(props)
this.state = {
days: [{text: 'Sofort', id: 1, selected: true}, {text: 'Morgen', id: 2, selected: false}, {text: 'Montag', id: 3, selected: false}, {text: 'Samstag', id: 4, selected: false}, {text: 'Sonntag', id: 5, selected: false}]
}
}
onDaySelection(selectedDay) {
// some logic to change the selected day
}
render() {
<Bar data={this.state.days} callback={this.onDaySelection(selectedDay)}>
}
}
バークラス:
class Bar extends Component {
constructor(props) {
super(props)
let dataSource = new ListView.DataSource(
{rowHasChanged: (r1, r2) => r1.id !== r2.id}
)
this.state = {
dataSource: dataSource.cloneWithRows(this.props.days),
}
}
componentWillReceiveProps(newProps) {
let dataSource = new ListView.DataSource(
{rowHasChanged: (r1, r2) => r1.id !== r2.id}
)
this.state = {
dataSource: dataSource.cloneWithRows(newProps.days),
}
}
renderRow(rowData) {
let tick = rowData.selected? (
<Image source={require('../assets/images/Checkbox.png')}/>
): (
<Image source={require('../assets/images/CheckboxEmpty.png')}/>
)
return (
<View>
<TouchableOpacity
onPress={() => {this.props.callback(rowData)}}
style={appStyles.flowRight}
>
{tick}
<Text>{rowData.text}</Text>
</TouchableOpacity>
</View>
)
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
/>
)
}
}
をあなたは私を見ることができるようにBarクラスにメソッドのcomponentWillReceivePropsを実装する必要がありましたが、これはなぜですか?なぜコンストラクタが再度呼び出されないのですか?ストアが更新されていないためですか?これは正しいパターンですか?
EDIT:
class CustomCarouselIndicator extends Component {
constructor(props) {
super(props)
}
render() {
let indicatorArray = []
for(let i = 0; i < this.props.length; i++) {
indicatorArray.push(i)
}
let indicators = indicatorArray.map(index => {
let isSelected = index == this.props.selected
//Some more logic
})
return (
<View style={[appStyles.flowRight, {flex: 1, justifyContent: 'center', alignItems:'center'}, this.props.style]}>
{indicators}
</View>
)
}
}
たびI:元、私の質問は明確ではなかった、小道具を受ける他のコンポーネントがあるという意味で、唯一のコンストラクタを持っており、彼らの小道具が更新されるたびに応じて更新するようです選択した小道具を変更すると、コンポーネントは更新され、componentWillReceivePropsを実装する必要はありません。
このクラスは両方ともコードベースで使用されていますが、私は小道具を受け取る実装が必要ですが、新しい小道具が渡されたときにコンポーネントを更新するために何もする必要はありません。
あなたがコードを書く前に、まず文書を読んでください。 https://facebook.github.io/react/docs/component-specs.html – xiaofan2406
https://facebook.github.io/react/docs/component-api.html#setstate – xiaofan2406