**ApplicatorType Stateful Component**
class ApplicatorType extends Component {
public state = {
applicatorTypes: ['Carpenter', 'Painter', 'Plumber'],
applicatorTypesSelected: [],
}
public render() {
allotedTypes = (
<DisplayTypes
applicatorTypes={this.state.applicatorTypes}
changed={this.typeCheckedHandler}
checkedType={this.state.applicatorTypesSelected}
/>
);
return <div> {allotedTypes} </div>
}
private typeCheckedHandler =
(event: React.ChangeEvent, selected: string) => {
const index = this.state.applicatorTypesSelected.indexOf(selected);
if (index < 0) {
this.state.applicatorTypesSelected.push(selected);
} else {
this.state.applicatorTypesSelected.splice(index, 1);
}
this.setState({
applicatorTypesSelected:[...this.state.applicatorTypesSelected]
});
};
}
**DisplayTypes Stateless Component**
import * as React from 'react';
import Checkbox from '../../UI/Checkbox/Checkbox';
const displayTypes: React.SFC<any> =
({applicatorTypes, changed, checkedType}) =>
applicatorTypes.map((element: string, index: number) => {
return
(<Checkbox
key={index}
changed={(event: React.ChangeEvent) => changed(event, element)}
checkedType={checkedType.some((x: string) => x === element)}
element={element}
/>);
})
export default displayTypes;
**Checkbox stateless component**
const checkbox: React.SFC<any> = ({ element, changed, checkedType}) =>
{
return (
<div>
<input
name={element}
className="checkbox"
type="checkbox"
onChange={changed}
checked={checkedType}
/>{' '}
<label onClick={changed}>{element}</label>
</div>
);
};
export default checkbox;
在上面的DisplayTypes组件中,
changed={(event: React.ChangeEvent) => changed(event, element)}
checkedType={checkedType.some((x: string) => x === element)}
推荐的方法是避免使用箭头功能。然而, 没有箭头功能,我无法使其工作。没有箭头功能,有没有更好的方法来实现相同的功能?
现在,我在tslint.json中使用“ jsx-no-lambda”:false,并且代码运行正常。
答案 0 :(得分:1)
您可以进行以下更改以避免使用lambda函数
private typeCheckedHandler =
(selected: string, event: React.ChangeEvent,) => {
...
...
};
并将组件更改为:
const DisplayTypes =
({ applicatorTypes, changed, checkedType }) => {
return applicatorTypes.map((element, index) => {
let list = checkedType.some((x: string) => x === element);
return (<Checkbox
key={index}
changed={changed.bind({}, element)}
checkedType={list}
element={element}
/>);
})
}
如有需要,随时发表评论。