반응형
하위 React 구성 요소에서 상위 메서드를 호출하려면 어떻게 해야 합니까?
부모 컴포넌트와 자녀 컴포넌트가 있는데 다음과 같이 자녀 컴포넌트의 부모 메서드를 호출합니다.
import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};
click() {
Parent.someMethod();
}
render() {
<div>Hello Child onClick={this.click}</>
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
};
someMethod() {
console.log('bar');
}
render() {
<div>Hello Parent</>
}
}
그러면 다음 오류 메시지가 반환됩니다.
Uncaught TypeError: _Parent2.default.someMethod is not a function
자식 구성 요소에서 이 부모 메서드를 호출하려면 어떻게 해야 합니까?
이거 먹어봐.기능을 소품으로 하위 구성요소에 전달합니다.
import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};
click = () => {
this.props.parentMethod();
}
render() {
<div onClick={this.click}>Hello Child</div>
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
};
someMethod() {
console.log('bar');
}
render() {
<Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
}
}
자녀에게 부모의 상태를 전달하여 부모의 기능을 호출하고, 자녀 수업에서 소품을 사용하여 호출을 하는 등의 시도를 할 수 있습니다.
class FlatListItem extends Component{
constructor(props){
super(props)
}
render(){
return(
<TouchableOpacity style={styles.button}
onPress=
{(item)=>this.props.parentFlatlist.delete(item)}></TouchableOpacity>
</Swipeout>
)
}}
이제 부모 클래스 Random List가 있다고 가정합니다.
class RandomList extends Component{
static navigationOptions = ({navigation}) =>{
return{
headerTitle: 'Random List'
}
};
state = {
lists : [],
refreshing : false
}
constructor(props){
super(props)
}
delete= (item) =>{
//delete your item
console.log(item)
}
render(){
return(
<BackgroundImageComponent>
<FlatList
keyExtractor={item => item}
data = {this.state.lists}
renderItem = {({item,index}) => (
<FlatListItem onPress={()=>this.seeTheList(item)} item1={item} parentFlatList={this} index={index}>
</FlatListItem>
)}
/>
</ScrollView>
</BackgroundImageComponent>
)
}}export default RandomList
여기를 보십시오. parentFlatlist={this}를 전달하고 나중에 자식 클래스에서 동일한 인스턴스를 사용합니다.코드에 초점을 맞추지 않고 삭제 기능을 렌더링할 수 있는 방법에 초점을 맞추는 것이 주된 생각입니다.코드가 잘못되었거나 고장났다면 용서해 주세요.
언급URL : https://stackoverflow.com/questions/40109698/how-can-i-call-parent-method-in-a-child-react-component
반응형
'programing' 카테고리의 다른 글
JSON에 대한 PDOStainment (0) | 2023.02.26 |
---|---|
MongoDB의 정확한 요소 배열 필드 업데이트 (0) | 2023.02.26 |
React state vs Redux Store를 선택하는 경우 (0) | 2023.02.26 |
gradle process 명령어 java가 0이 아닌 exit 값 1로 종료되었습니다. (0) | 2023.02.26 |
get_posts()는 9를 반환해야 하는데 왜 일치하는 게시물을 5개만 반환합니까? (0) | 2023.02.26 |