代码之家  ›  专栏  ›  技术社区  ›  tuimui

使用react+ts通过道具传递数据

  •  1
  • tuimui  · 技术社区  · 1 年前

    我试着从这里开始做快速入门教程: https://react.dev/learn/tutorial-tic-tac-toe 在ts而不是js中。 怎么了?上面写着: 声明了“number”,但从未读取其值。ts(6133) 绑定元素“number”隐式具有“any”类型。ts(7031)

    export default function Board(){
      return (
        <>
          <div className="board-row">
            <Square value={1}/>
            <Square value={2}/>
            <Square value={3}/> 
          </div>
          <div className="board-row">
            <Square value={4}/>
            <Square value={5}/>
            <Square value={6}/>
          </div>
          <div className="board-row">
            <Square value={7}/>
            <Square value={8}/>
            <Square value={9}/>
          </div>
        </>
      );
    }
    
    function Square({value: number}){
      return <button className="square">{value}</button>;
    }
    

    上面写着: 声明了“number”,但从未读取其值。ts(6133) 绑定元素“number”隐式具有“any”类型。ts(703

    1 回复  |  直到 1 年前
        1
  •  0
  •   zouabi    1 年前

    在您的示例中,您使用 destructuring

    function Square({value: number}) {
      // ...
    }
    // is equivalent to:
    function Square({ value: number }: any) {
      // ...
    }
    // or
    function Square(props: any) {
      const number = props.value;
    
      // ...
    }
    
    
    // what you want is providing the type for the props:
    function Square({ value }: { value: number }) {
     // ...
    }
    
    // or
    interface SquareProps {
      value: number;
    }
    
    function Square({ value }: SquareProps) {
     // ...
    }
    
    // which is equivalent to:
    function Square(props: SquareProps) {
     const value = props.value;
     // ...
    }
    

    祝你的学习之旅好运!