首页 > 解决方案 > 如何为反应组件提供 Id 或 Attribute

问题描述

我们需要为我们的 react 组件提供一些标识符,以便我们可以在这些控件上编写自动化测试用例。

import React from 'react';
import ReactDOM from 'react-dom';
import { Grid, GridColumn as Column } from '@progress/kendo-react-grid';

import products from './products.json';

class App extends React.Component {
    state = {
        gridData: products
    }

    render() {
        return (
            <div>
                <Grid
                    data-grid="myGrid"
                    style={{ height: '400px' }}
                    data={this.state.gridData}
                >
                    <Column field="ProductID" title="ID" width="40px" />
                    <Column field="ProductName" title="Name" width="200px" />
                    <Column field="Category.CategoryName" title="CategoryName" />
                    <Column field="UnitPrice" title="Price" width="80px" />
                    <Column field="UnitsInStock" title="In stock" width="80px" />
                    <Column field="Discontinued" width="120px"
                        cell={(props) => (
                            <td>
                                <input disabled type="checkbox" checked={props.dataItem[props.field]} />
                            </td>
                        )} />
                </Grid>
            </div>
        );
    }
}

ReactDOM.render(
    <App />,
    document.querySelector('my-app')
);

我们试图为网格提供data-grid="myGrid"属性,但这似乎不起作用。您能否建议这里的错误是什么或解决方案是什么。

标签: htmlreactjsreact-nativekendo-uicustom-data-attribute

解决方案


你应该使用 prop 传递camelCase它应该是这样的:

<Grid dataGrid="myGrid" />

在里面Grid你可以像这样指定它:

const Grid = ({dataGrid}) => (
   <div data-grid={dataGrid} />
)

或者您可以设置id为组件<Grid id="myGrid" />


推荐阅读