我有一个可选择的列表,其中包含其网站上的确切代码:
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem, makeSelectable} from 'material-ui/List';
import Avatar from 'material-ui/Avatar';
import Subheader from 'material-ui/Subheader';
let SelectableList = makeSelectable(List);
function wrapState(ComposedComponent) {
return class SelectableList extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
defaultValue: PropTypes.number.isRequired,
};
componentWillMount() {
this.setState({
selectedIndex: this.props.defaultValue,
});
}
handleRequestChange = (event, index) => {
this.setState({
selectedIndex: index,
});
};
render() {
return (
<ComposedComponent
value={this.state.selectedIndex}
onChange={this.handleRequestChange}
>
{this.props.children}
</ComposedComponent>
);
}
};
}
SelectableList = wrapState(SelectableList);
const ListExampleSelectable = () => (
<MobileTearSheet>
<SelectableList defaultValue={3}>
<Subheader>Selectable Contacts</Subheader>
<ListItem
value={1}
primaryText="Brendan Lim"
leftAvatar={<Avatar src="images/ok-128.jpg" />}
nestedItems={[
<ListItem
value={2}
primaryText="Grace Ng"
leftAvatar={<Avatar src="images/uxceo-128.jpg" />}
/>,
]}
/>
<ListItem
value={3}
primaryText="Kerem Suer"
leftAvatar={<Avatar src="images/kerem-128.jpg" />}
/>
<ListItem
value={4}
primaryText="Eric Hoffman"
leftAvatar={<Avatar src="images/kolage-128.jpg" />}
/>
<ListItem
value={5}
primaryText="Raquel Parrado"
leftAvatar={<Avatar src="images/raquelromanp-128.jpg" />}
/>
</SelectableList>
</MobileTearSheet>
);
export default ListExampleSelectable;
我希望能够在另一个函数中获取更新的selectedIndex的值,但我尝试做
export default class Parent extends React.Component {
componentWillMount() {
this.setState({
selectedIndex: this.props.defaultValue,
});
}
handleRequestChange = (event, index) => {
this.setState({
selectedIndex: index,
});
};
render(){
<SelectableList index={this.state.selectedIndex} change=
{this.handleRequestChange} />
}
}
然后我用
更改SelectableList类的render函数<ComposedComponent
value={this.props.index}
onChange={this.props.change}
>
{this.props.children}
</ComposedComponent>