简体   繁体   English

Reactjs - 将 API 数据作为道具传递给自动完成组件(Material-UI)

[英]Reactjs - Passing API data as props for Autocomplete component (Material-UI)

I am a beginner in Reactjs.我是 Reactjs 的初学者。 I am trying to implement the Autocomplete component provided by material-ui.我正在尝试实现 material-ui 提供的自动完成组件。 I want to pass the API link as a prop to the element.我想将 API 链接作为道具传递给元素。 But how to pass the json label name as a prop to be used in "getOptionLabel"?但是如何将 json label 名称作为要在“getOptionLabel”中使用的道具传递? For example, If we consider this API link which returns TV Show names, we need to use SHOW.NAME to access the name of the show.例如,如果我们考虑这个返回电视节目名称的 API 链接,我们需要使用 SHOW.NAME 来访问节目的名称。

getOptionLabel={(option) => option.show.name}

Here, the dynamic part is 'show.name'.这里,动态部分是“show.name”。 How to pass this as prop?如何将此作为道具传递? I tried doing我试着做

const label = 'show.name'

and then接着

getOptionLabel={(option) => option.label}

But his wouldn't work.但他的行不通。

You need to pass the props in the function.您需要通过 function 中的道具。 You could do something like this:你可以这样做:

export default function App() {
  const someData = [{
    name: "abc"
  }]
  return ( <
    Autocomplete myOptions={someData} />
  );
}


export default function ComboBox(props) {
  return ( <
    Autocomplete id = "combo-box-demo"
    options = {
      props.myOptions
    }
    getOptionLabel = {
      (option) => option.name
    }
    style = {
      {
        width: 300
      }
    }
    renderInput = {
      (params) => < TextField { ...params
      }
      label = "Combo box"
      variant = "outlined" / >
    }
    />
  );
}

See it live here在这里看到它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM