【问题标题】:React can't pass props to componentReact 无法将道具传递给组件
【发布时间】:2020-12-21 23:14:11
【问题描述】:

我无法将道具从 App.tsx 传递给我的子组件,我不知道为什么。我已经在网上看了 2 个小时,但没有有效的解决方案。有谁知道问题是什么?它也给了我以下错误:

"没有重载匹配这个调用。 Overload 1 of 2, '(props: Readonly): CartView', 给出了以下错误。 输入'{短语:字符串; }' 不可分配给类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly'。 类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly'。 Overload 2 of 2, '(props: Props, context?: any): CartView',给出了以下错误。 输入'{短语:字符串; }' 不可分配给类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly'。 类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly'.ts(2769)"

组件

import React, { Component } from 'react';

class CartView extends Component<Props, State>{
    render(){
        return(
            <div>
                <p>{this.props.phrase}</p> <--- This doesn't work. It only autofills to use this.props.children.
            </div>
        )
    }
}

export default CartView;

App.tsx

import React from 'react';
import CartView from './components/cart/Cart';

type Props = {};
type State = {};

function App() {
  return (
    <div className="App">
      <CartView phrase="Hello"/>
    </div>
  );
}

export default App;

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您已为组件 Cartview 使用了 PropsState 接口

    import React, { Component } from 'react';
    
    // Create Interface 
    interface Props {
        phrase: string
    }
    
    class CartView extends Component<Props, {}>{
        // add a constructor 
        constructor(props: Props) {
            super(props);
        }
        render() {
            return (
                <div>
                    <p>{this.props.phrase}</p> 
                </div>
            )
        }
    }
    
    export default CartView;
    

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 2017-02-19
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      相关资源
      最近更新 更多