代码之家  ›  专栏  ›  技术社区  ›  Prasaad Patil

如何显示传递给组件的参数,以及如何在reactjs中为组件提供可选参数?

  •  2
  • Prasaad Patil  · 技术社区  · 8 年前

    我正在visual studio 2017中使用react with typescript开发一个网页,我对它非常陌生。我在访问传递给组件的参数和使参数可选时遇到一些问题。下面是我的代码:-

    路线。tsx:

    export const routes = <Layout>
    <Switch>
        <Route path='/home/:id' component={Home} /> //<= this works, but i want id parameter to be optional. I tried (/:id) but the component does not render if i do this.
    </Switch>
    </Layout>
    

    家tsx:

    export class Home extends React.Component<RouteComponentProps<{}>, {}> {
    public render() {
        console.log(this.props.match.params); //<= I can see the id which i pass in the console
        return <div>
           <h1>{this.props.match.params}<h1> //<= this does not work and gives me a runtime error 'Unhandled rejection Invariant Violation: Objects are not valid as a React child (found: object with keys {id}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons'
       </div>
    

    1) 如何为组件提供可选参数?
    2) 如何在主元件中显示传递的参数?

    任何帮助都将不胜感激。提前感谢

    3 回复  |  直到 8 年前
        1
  •  2
  •   pgsandstrom    8 年前

    使用 ? 这样可以传递可选参数:

    <Route path="/home/:id?" component={Home}/>

    Start reading here 了解更多信息

    要显示变量,请使用 {this.props.match.params.id} 。如果要处理id不存在的情况,可以使用类似的方法:

    {this.props.match.params.id || 'sorry lol no id is specified'}

    为了澄清出现错误的原因:“params”是一个包含所有参数的对象。React不知道如何显示对象。如果要显示对象,可以使用 JSON.stringify(params) 但我认为这不是你想要的。

        2
  •  2
  •   Prasaad Patil    8 年前

    使用 ? 正如@pgsandstrom所说,传递一个可选参数对我有用。

    至于从params检索id属性,我所做的就是为此创建一个对象。道具。火柴params,然后使用该对象检索id。以下是我使用的代码:-

    let data = Object.create(this.props.match.params);
    

    然后

    data.id
    

    将检索我的id,而不会在typescript中提供任何编译错误

        3
  •  0
  •   LukáÅ¡ Gibo Vaic    8 年前

    问题是您想要渲染对象,因为这是。道具。火柴params指向整个对象,所以您要么必须字符串化,要么请求Id之类的特定属性。

    {JSON.stringify(this.props.match.params)}
    

    {this.props.match.params.id}
    ofcourse that for this thing you have to accept id as parametr /home/:id
    

    由于您使用的是typescript,这取决于您是在编写类(组件)还是函数,无论哪种方式,您都会遇到错误,因为您没有正确键入它,但由于您正在引用它。道具,我将承担它的等级。

    class App extends React.Component<Props> {}
    
    interface Props {
        match: any;
    }
    

    是的,它的键入能力很弱,但除非你直接从库中导入键入,否则你需要花一段时间才能键入全部内容,而且在每个文件中都这样做会很愚蠢。