【问题标题】:How to send prop value using function in react js/react native如何使用 react js/react native 中的函数发送道具值
【发布时间】:2020-07-21 17:52:27
【问题描述】:

在我的应用程序中,我使用了一个 ErrorMessage 组件,该组件负责以不同颜色的不同消息在 Text 中显示错误消息。

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

export default class ErrorMessage extends Component {
constructor(props) { 
super(props);

this.state = {
};
}

render() {
  //console.log("props:",this.props);
  //debugger;
return (
  <View style={styles.form}>
    <Text style={{color:this.props.color}}> {this.props.ErrorMessage} </Text>
  </View>
);
}

}
const styles = StyleSheet.create({
form: {
},
});

我尝试在以下可能的情况下使用我的组件

<ErrorMessage ErrorMessage={()=>{getMessage()}} color={props.color} />
  or 
<ErrorMessage ErrorMessage={getMessage} color={props.color} />
or
<ErrorMessage ErrorMessage={getMessage()} color={props.color} />

我的 getMessage 函数如下所示

 const getMessage = ()=> {
 console.log("get message:state"+state)
   if (state == 2) {
      // error
      return "Please enter valid user id";
   }
   if (state == 3) {
      // warning
      return "Please enter min 3 char";
   }  else {
      // success
     return "Valid user id";
   }

};

但在所有情况下,应用程序都会抛出警告 “React Native – 警告:函数作为 React 子级无效。如果您返回组件而不是从渲染中返回,则可能会发生这种情况。或者您可能打算调用它函数而不是返回它。"* 并且应用程序没有执行 getMessage 函数体"*

请建议我们如何使用函数返回数据向组件发送道具。

【问题讨论】:

  • 只有&lt;ErrorMessage ErrorMessage={getMessage()} color={props.color} /&gt; 适合您。因为 ErrorMessage 是 string/int 类型,但您在前两种情况下传递函数。
  • 感谢它的帮助。我将 const 重命名为函数并按照你的 cmets 调用。

标签: reactjs react-native react-component


【解决方案1】:

重命名道具,并像这样称呼它

<ErrorMessage Message={getMessage()} color={props.color} />

【讨论】:

    猜你喜欢
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多