problem description
recently encountered such a problem in development, for a simple Dialog component:
- in the way of a controlled component, the callback function of receiving the parent component through props triggers to change the state value
- using uncontrolled components, change the state value by calling subcomponents through ref
related codes
/ / Please paste the code text below (do not replace the code with pictures)
- uncontrolled components
export default class extends Component {
constructor(props) {
super(props);
this.state = { visible: false };
}
show() {
this.setState({
visible: true
})
}
onCancel(){
this.setState({
visible: false,
})
}
render() {
return (
<Modal
visible={this.state.visible}
onRequestClose={() => {
if(this.state.visible) { this.setState({ visible: false })}
}}>
<Button onPress={() => this.onCancel()}></Button>
</Modal>
);
}
}
- controlled components
export default function (props){
if (!props.visible) {
return null;
}
return (
<Modal visible={props.visible} onRequestClose={props.onCancel}
<Button onPress={props.onPress}></Button>
</Modal>
);
}
- parent component
<>
<Button onPress={this.setState({ visible: true })}>
<Button onPress={this.ref.show}>
< ref={ref => { this.ref = ref }} />
<
visible={this.state.visible}
onPress={this.setState({
visible: false
})}
/>
</>
what result do you expect? What is the error message actually seen?
React recommends the use of controlled components, but I found
in actual use.- uses uncontrolled components. Uncontrolled components are rendered when the parent component is rendered for the first time, and then the state is changed by calling the method of the uncontrolled component through ref. The state change renders the uncontrolled component, but does not render the parent component repeatedly
- uses a controlled component, which does not render the controlled component when the parent component renders for the first time, but when the state changes, the controlled component renders again because setState () is in the parent component, and the parent component renders
so which of the two performs better under the same effect?