嗨,我在React项目中遇到一些问题,我正在使用钩子,并且我将作为道具传递给钩子的方法遇到了问题。我也在使用materail ui,这是我的代码:
import { Container, Grid, Select, MenuItem } from '@material-ui/core';
import React, { Component } from 'react';
import Store from '../component/store/store'
class StoreBuilder extends Component {
state = {
DivisionState: 'Store 1',
DivisionData: [
{
id: 1,
divDeptShrtDesc: 'Store 1'
},
{
id: 2,
divDeptShrtDesc: 'Store 2'
},
{
id: 3,
divDeptShrtDesc: 'Store 3'
}
]
};
handleChangeDivision(event) {
this.setState({ DivisionState: event.target.value });
}
renderDivisionOptions() {
return this.state.DivisionData.map((dt, i) => {
return (
<MenuItem
key={i}
value={dt.divDeptShrtDesc}>
{dt.divDeptShrtDesc}
</MenuItem>
);
});
}
render() {
return (
<div>
<Container >
<Grid >
<Store stores={this.state.DivisionState}
onChange={this.handleChangeDivision}
render ={this.renderDivisionOptions()}>
</Store>
</Grid>
</Container>
</div>
);
}
}
export default StoreBuilder;
接下来是挂钩代码:
import { Container, Grid, Select, MenuItem } from '@material-ui/core';
import React, { Component } from 'react';
const store = (props) => {
return (
<div>
<Container >
<Grid >
<Select value={props.DivisionState}
onChange={props.handleChangeDivision}
>
{() =>props.render()}
</Select>
</Grid>
</Container>
</div>
);
}
export default store;
问题出在下一个代码中,我不太确定是否可以做下一个代码,我试图将renderDivisionOptions方法作为参数传递给与道具挂钩使用的参数:< / p>
{() =>props.render()}
答案 0 :(得分:0)
您正在将函数{() =>props.render()}
传递到<Select>
,但是似乎您需要调用该函数:
<Select value={props.DivisionState}
onChange={props.handleChangeDivision}
>
{props.render()}
</Select>
此外,如果Select
元素需要一个ReactNode,则可能需要用一个片段将其包装起来:
<>{props.render()}</>
由于您将renderDivisionOptions
作为回调传递给另一个组件,因此它将丢失其上下文(this
)。您需要将其转换为箭头函数,或将其绑定到构造函数中。
renderDivisionOptions = () => {
return this.state.DivisionData.map((dt, i) => {
return (
<MenuItem
key={i}
value={dt.divDeptShrtDesc}>
{dt.divDeptShrtDesc}
</MenuItem>
);
});
}