【问题标题】:How to use props in a function in class component?如何在类组件的函数中使用道具?
【发布时间】:2021-08-10 13:15:52
【问题描述】:

我有问题。我使用 React Router 来检查 URL 路径。

<Route path="/:brand" component={Container} />

我在Container组件中使用过

import React from 'react';
import CarPage from '../components/CarPage';
import '../styles/Container.css';

const Container = ({ match }) => {
    return (
       <CarPage brand={match.params.brand} />
   );
}

export default Container;

在组件中,我想在“findMyIndex”函数中使用它来检查它在“carList”数组中的索引

import React, { Component } from 'react';

class CarPage extends Component {
    state = {
        index: 0,
    }
    carList = ["Ford", "Fiat", "Ferrari"];

    findMyIndex = (props.brand) => {
        console.log(props.brand);    
    }
    render() {
        return (
            <p>{this.props.brand}</p>
        );
    }
}

export default CarPage;

然后他必须在this.state.index中输入找到的索引。问题是我不知道如何在类组件的函数中正确使用道具。我是初学者,想知道如何在“findMyIndex”中正确使用“brand”。请帮忙。

【问题讨论】:

  • 我从来没有使用过类,但是由于箭头函数继承了上下文,this.props.brand 不工作吗? (根本没有将值传递给箭头函数)

标签: reactjs react-router react-props react-component


【解决方案1】:

你的道具可以在课堂上的任何地方访问。您可以像这样在 findMyIndex 方法中访问它:

findMyIndex = () => {
    console.log(this.props.brand);    
}

【讨论】:

  • 谢谢它的工作!我还有一个问题,如何在段落下调用函数“findMyIndex”?
  • 这个函数有什么作用?它返回什么?
  • 这个函数在你的答案中,我正在尝试这样的事情,但这不起作用:{this.findMyIndex()}
  • 到目前为止,除了将品牌打印到控制台之外,您的函数没有做任何事情。
  • 是的,我只是不知道如何让它显示在控制台上。这样的事情不起作用:render(){return(&lt;p&gt;{this.props.brand}&lt;/p&gt;{this.findMyIndex()})}
猜你喜欢
  • 1970-01-01
  • 2021-01-14
  • 2020-05-25
  • 1970-01-01
  • 1970-01-01
  • 2022-07-19
  • 1970-01-01
  • 2019-12-29
  • 1970-01-01
相关资源
最近更新 更多