首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在React本机typescript类组件中使用扩展运算符

如何在React本机typescript类组件中使用扩展运算符
EN

Stack Overflow用户
提问于 2021-09-24 10:37:23
回答 2查看 0关注 0票数 0

我正在处理我的FormButton.tsx文件。我使用的是React native和TypeScript:

代码语言:javascript
运行
复制
interface Props {
  buttonTitle: string;
  restProps: any;
}

interface State {}

export default class FormButton extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
  }

  render() {
    const {buttonTitle, ...restProps} = this.props;
    return (
      <TouchableOpacity>
        <Text>{buttonTitle}</Text>
      </TouchableOpacity>
    );
  }
}

正如你注意到的,对于restProps,我正在尝试接收这个道具给出的其余道具。但是,这将返回一个错误'restProps' is declared but its value is never read.ts(6133)

基本上,我想要完成的是能够在const {buttonTitle, ...restProps} = this.props;中解析restProps,然后能够在我的TouchableOpacity上使用它。

你知道怎么解决这个问题吗?

更新:我认为这里有一些混乱。我不是在说简单地接受一个特定的道具。如果我有3个或更多未指定的道具怎么办?如何通过TypeScript在类组件中传播它们。通常,你会在一个普通的功能组件中看到类似这样的东西:

代码语言:javascript
运行
复制
const FormButton = ({buttonTitle, ...rest}) => {
  return (
    <TouchableOpacity style={styles.buttonContainer} {...rest}>
      <Text style={styles.buttonText}>{buttonTitle}</Text>
    </TouchableOpacity>
  );
};

如何将其转换为TypeScript和React本地类组件?

EN

回答 2

Stack Overflow用户

发布于 2021-09-24 10:45:19

像这样解构一个对象,

代码语言:javascript
运行
复制
const {buttonTitle, restProps} = this.props;

现在您将拥有两个变量buttonTitlerestProps

票数 0
EN

Stack Overflow用户

发布于 2021-11-20 21:47:58

@哈里特·拉斯托吉的答案是正确的。而是为功能组件用户提供道具界面。

代码语言:javascript
运行
复制
import React from "react";
import { StyleSheet, Text, TouchableOpacity } from "react-native";

interface Props {
  buttonTitle: string;
  [x: string]: any;   //please comment if you know better type than any
}

const FormButton: React.FC<Props> = (props) => {
  const { buttonTitle, ...rest } = props;
  return (
    <TouchableOpacity style={styles.buttonContainer} {...rest}>
      <Text style={styles.buttonText}>{buttonTitle}</Text>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  // Your button-container style here
  buttonContainer: {},
  buttonText: {},
});

export default FormButton;

然后你可以像这样使用它:

代码语言:javascript
运行
复制
 <FormButton
        buttonTitle="Testing Button"
        onPress={() => console.log("foo")}
 />

如果您只想添加样式:

代码语言:javascript
运行
复制
import React from "react";
import { StyleProp, StyleSheet, View, ViewStyle } from "react-native";

interface Props {
  style?: StyleProp<ViewStyle>;
}
const Card: React.FC<Props> = ({ children, style }) => {
  return <View style={[styles.card, style]}>{children}</View>;
};

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

export default Card;

然后你可以像这样使用(你也会得到自动补全):

代码语言:javascript
运行
复制
 <Card style={{ width: 500 }}>
 </Card>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69313605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档