【问题标题】:React-Admin: How can I access a value without `source`?React-Admin:如何在没有“源”的情况下访问值?
【发布时间】:2020-01-30 07:01:49
【问题描述】:

我正在尝试在react-admin 中创建一个动态按钮。
对于每个按钮,它都会点击一个唯一的地址,我该怎么做?

很遗憾,我遇到了这个错误:props.username is undefined

export const LoginCredentialList = (props) => (
  <List {...props} pagination={<PostPagination/>}>
    <Datagrid>
       <TextField label="Username" source="username" />
       <Button label="Re-invoke Login"
          onClick={() => {       
            axios.get("http://localhost:8080/admin/" + somehow_read_username_here)
                 .then((res)=>console.log(res));
             }}
        />
    </Datagrid>
  </List>
);

这里是parent,上面的组件被调用或使用:

class SPanel extends React.Component {
  render() {
    return (
      <div>
        <Admin dataProvider={restDataProvider}>
          <Resource name="loginCredential" list={LoginCredentialList} />
            ...

【问题讨论】:

  • 请提供问题的详细信息
  • 如何将用户名属性传递给 LoginCredentialList 组件?
  • 已更新,请参阅@JatinParmar .. 这是我的两个组件..
  • @krisaoe 我不熟悉,你能告诉我怎么做吗??
  • @Danial Resource 如何渲染 LoginCredentialList?

标签: reactjs react-admin


【解决方案1】:

我之前没有使用过react-admin,但是在快速浏览了它的文档之后,我了解到

  • 您在LoginCredentialList 组件中收到的props 包含记录列表
  • Datagrid 遍历此列表并将单个 record 传递给子 Field 组件
  • Field 组件接收 record 作为由 react-admin 注入的 prop

虽然react-admin 提供了许多标准的Field 组件,但它没有ButtonField

因此您可以编写自己的Field 组件。 (https://marmelab.com/react-admin/Fields.html#writing-your-own-field-component)

类似:

const ButtonField = ({source, record}) => (
    <Button label="Re-invoke Login" onClick={()=>{
        axios
            .get("http://localhost:8080/admin/"+record[source])
            .then((res)=>console.log(res));
    }}/>
);

然后用它作为你的主要组件

export const LoginCredentialList = (props) => (
    <List {...props} pagination={<PostPagination/>}>
        <Datagrid>
            <TextField label="Username" source="username" />
            <ButtonField source="username" />
        </Datagrid>
    </List>
);

试试这个。

【讨论】:

    猜你喜欢
    • 2011-07-31
    • 2012-10-21
    • 1970-01-01
    • 2023-02-04
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多