reactjs - 使用 TypeScript 进行 react : passing a number variable to a child component

标签 reactjs typescript

我试图将一个数字变量传递给组件,但 React 似乎将其转换为字符串。

这段代码:

interface Props {
  variable: number
  literal: number
}

const Parent = () => {
  const num = 2
  return <Child literal={1} variable={num}/>
}

const Child: React.SFC<Props> = (props) => {
  console.log(typeof props.variable)
  console.log(typeof props.literal)
  return <div/>
}

ReactDOM.render(<Parent/>, document.querySelector('#root'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

将打印:

string
number

如何让 React 在传递变量时保留变量的类型?

最佳答案

我做了这样的事情

type Props = {
  literal: number
  variable: number
}

function Child(props: Props): JSX.Element {
  console.log(typeof props.literal)
  console.log(typeof props.variable)

  return <div />
}

function Parent(): JSX.Element {
  const num: number = 2

  return (
    <Child literal={1} variable={num}/>
  )
}

const rootElement = document.getElementById("root");
render(<Parent />, rootElement);

检查 codesandbox 中的控制台

关于reactjs - 使用 TypeScript 进行 react : passing a number variable to a child component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51092934/

相关文章:

javascript - Material UI 选项卡 : After switch between tabs, 选项卡中的更改被丢弃

javascript - 将 React 组件作为 props 传递

javascript - 如何将 Angular 应用程序中的对象数组从一个组件传递到另一个组件

typescript - 扩展运算符剥离 typescript 中的类型定义

reactjs - 使用 create-react-app 和 webpack 发出 CORS API 请求 - 无 express

javascript - 当我在 react 中更新状态时,这是我避免改变状态的方法吗?

javascript - React Native 元素列表项开关不起作用

javascript - 什么是双箭头函数?

javascript - 有没有办法让一组类方法知道调用何时终止?

typescript 找不到模块 'wnumb'