【问题标题】:The pre-configured props set from within the React child is overriding the custom props passed from the parent从 React 子级中设置的预配置道具覆盖了从父级传递的自定义道具
【发布时间】:2021-07-31 02:45:14
【问题描述】:

显示的是 fontSize: 20 和 color: 'red' 属性,而不是从 Parent 组件设置的 fontSize: 12 和 color: 'blue',但 fontWeight: 'bold' 正确显示。

我有一个可重用的 React UI 子组件,它像这样从其父组件接收一些道具

import React from "react";
import { Text, StyleSheet } from "react-native";

const BodyText = ( props ) => {
  return (
      <Text style={styles.bodyText} {...props} >{props.children}</Text>
  );
};
const styles = StyleSheet.create({
  bodyText: {
    fontSize: 20,
    color: 'red'
  },
});

export default BodyText;

父组件长这样

import React from "react";
import { StyleSheet } from "react-native";
import BodyText from './components/UI/BodyText'

const Parent = () => {
  return (
      <BodyText style={styles.text} >Hi There</BodyText>
  );
};
const styles = StyleSheet.create({
  text: {
    fontSize: 12,
    color: 'blue',
    fontWeight: 'bold'
  },
});

export default Parent;

有趣的是,当我在CodePen 中玩耍时,它可以正确显示,但在我的本地设置中却没有。

【问题讨论】:

    标签: javascript reactjs react-native react-props


    【解决方案1】:

    像这样实现你的BodyText.js

    import React from 'react';
    import { Text, StyleSheet } from 'react-native';
    
    const BodyText = (props) => {
      const { style, children, ...rest } = props;   // Destructure props here...
    
      return (
        <Text style={[styles.bodyText, style]} {...rest}>
          {children}
        </Text>
      );
    };
    const styles = StyleSheet.create({
      bodyText: {
        fontSize: 20,
        color: 'red',
      },
    });
    
    export default BodyText;
    

    Working Example Snack

    【讨论】:

    • 感谢您的帮助。这是一个 100% 有效的代码,应该可以工作,但不幸的是,我仍然没有得到想要的输出。与以前没有任何变化。我在控制台记录了 props.style,奇怪的是它最初使用道具渲染了正确的对象,然后在最后一次渲染中,它渲染了一个空对象。
    【解决方案2】:

    您也可以使用默认道具:

    
    import React from "react";
    import { Text, StyleSheet } from "react-native";
    
    const BodyText = ( props ) => {
      return (
          <Text style={{
                    fontSize: props.fontSize,
                    color: props.color
                    }}>
                 {props.children}</Text>
      );
    };
    
    BodyText.defaultProps = {
       fontSize:20,
       color:'red'
    }
    
    export default BodyText;
    

    在你可以用新的道具使用你的组件之后:

     <BodyText fontSize={12} color='blue'>Hi There</BodyText>
    

    【讨论】:

    • 谢谢,是的,这应该可以,但在我的情况下不行。我控制台记录了道具,它在最后一次渲染中渲染了一个空对象。有趣的是它正确设置了其他样式。
    • 你检查我提供的零食了吗
    • @KartikeyVaish 是的,我做到了,它正在工作。正如我在您的代码之前所说的那样,它有效并且应该可以工作,我认为即使我的代码也应该可以工作。当我在本地系统中对其进行测试时,没有任何效果。一些奇怪的问题,我无法理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多