Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在React Native中向自定义视图上的样式表传递道具?_Reactjs_Typescript_React Native - Fatal编程技术网

Reactjs 如何在React Native中向自定义视图上的样式表传递道具?

Reactjs 如何在React Native中向自定义视图上的样式表传递道具?,reactjs,typescript,react-native,Reactjs,Typescript,React Native,因此,我有一个自定义视图。在这个视图中,除了使用子组件,我还想使用backgroundColor和其他一些样式表属性,以便根据屏幕设置样式 这是App.tsx export const MainScreen = ({}: Props) => { return ( <CustomView backgroundColor={"#000"}> <Text>Example</Text> </CustomV

因此,我有一个自定义视图。在这个视图中,除了使用子组件,我还想使用backgroundColor和其他一些样式表属性,以便根据屏幕设置样式

这是App.tsx

export const MainScreen = ({}: Props) => {
  return (
    <CustomView backgroundColor={"#000"}>
      <Text>Example</Text>
    </CustomView>
  );
};
export const MainScreen=({}:Props)=>{
返回(
例子
);
};
这是CustomView.tsx

type Props = {
  children: React.ReactNode;
  backgroundColor: string;
};

export const CustomView = ({ children, backgroundColor }: Props) => {
  return <View style={styles.container}>{children}</View>;
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

类型道具={
子节点:React.ReactNode;
背景颜色:字符串;
};
export const CustomView=({children,backgroundColor}:Props)=>{
返回{children};
};
const styles=StyleSheet.create({
容器:{
弹性:1,
辩护内容:“中心”,
对齐项目:“中心”,
},
});
比如说,我想把这个屏幕的背景色改为#000,就像上面的代码一样。但是,我不知道如何处理CustomView上的道具,以便它可以更改背景颜色

我试着写这个代码

return <View style={styles.container, {backgroundColor: backgroundColor}}>{children}</View>;
返回{children};
但它会覆盖styles.container。另一方面,如果我写这个

return <View style={{backgroundColor: backgroundColor}, styles.container}>{children}</View>;
返回{children};
它总是抛出一个错误,即逗号的左侧(背景色本身)未使用,并且没有副作用


那么,我该怎么办?如何传递道具来处理样式表?

您可以将数组传递给
样式
道具

根据报告:

style prop可以是一个普通的旧JavaScript对象。这就是我们通常使用的示例代码。您还可以传递样式数组-数组中的最后一个样式具有优先级,因此您可以使用它来继承样式

返回{children};

我想你是说React Native而不是React?@KevinAmiranoff是的,我就是这个意思。我应该说是本地人。我要编辑标题和标签。哇,太简单了。我忘了我必须使用数组。谢谢
return <View style={[styles.container, { backgroundColor: backgroundColor }]}>{children}</View>;