【问题标题】:Call parent function from Child component not working从子组件调用父函数不起作用
【发布时间】:2019-09-21 14:01:24
【问题描述】:

我有 2 个父组件(LoginScreen)和一个子组件(SignupSection)。子组件有 onClick 按钮。当用户单击按钮时,我需要从父组件触发功能,这对我不起作用。我有以下代码

我想从子组件调用父函数

父母

import React, {Component} from 'react';
import Wallpaper from './Wallpaper';
import SignupSection from './SignupSection';

export default class LoginScreen extends Component {
   constructor(props) {
     super(props)
   }

   childcall()
   {
     alert("hello , this call from child component");
   }

   render() {
     return (
      <Wallpaper>
      <SignupSection 
        childcall ={this.childcall.bind(this)} 
      />
      </Wallpaper>
      );
    }
   }

孩子

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {StyleSheet, View, Text} from 'react-native';


export default class SignupSection extends Component {
    constructor(props) {
       super(props)
    }
    componentWillMount()
    {

    }

    render() {
       return (
          <View style={styles.container}>
            <Text style={styles.text}  onClick={()=>this.props.childcall()}>Create Account</Text>
           <Text style={styles.text}>Forgot Password?</Text>
          </View>
       );
    }
 }

【问题讨论】:

标签: react-native react-redux jsx


【解决方案1】:

文本没有onClick。只有onPress 或者您应该将您的文本组件包装在TouchableOpacity 中,然后在onPress 中调用您的回调

修复:

return (
         <View style={styles.container}>
            <Text style={styles.text}  onPress={()=>this.props.childCall()}>Create Account</Text>
           <Text style={styles.text}>Forgot Password?</Text>
          </View>
       );

【讨论】:

  • 谢谢它的工作,但知道为什么我得到这个错误 _this.props.childcall is not a function。 (在 '_this2.props.childcall()' 中未定义)@Vivek_Neel
  • 您正在传递childCall 并调用this.props.childcall 检查大小写。
  • @JuniusL。我很抱歉我有点新反应原生你的意思是检查案例?
  • childCall 不是 childcall
  • @Vivek_Neel 我确实将所有内容都更改为 childcall Case,我更新了问题,但我仍然遇到同样的错误
猜你喜欢
  • 2020-03-25
  • 1970-01-01
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
  • 2021-02-03
  • 2020-12-22
  • 1970-01-01
相关资源
最近更新 更多