Bry*_*yan 2 javascript reactjs
使用React而不使用jQuery或任何其他库来实现这个jQuery 小提琴的最简单方法是什么?我还没有ReactJS技能,并且想知道是否有动态创建和删除元素的方法.
我在想创造一个
this.state = { "inputs": ["<input type="text" /><input type="checkbox" />"] }
Run Code Online (Sandbox Code Playgroud)
状态变量数组,在添加时保存HTML,为每个人提供一个基于索引的唯一键,然后是.map()它,但不确定是否有更简单的方法来实现这一点,并且不确定如何删除每个元素.
希望得到任何帮助或反馈,谢谢!
Yic*_*aoz 11
这是一种"React"方式,我不是React专家,所以代码可能会更好,会接受更正.
Row组件分成两个具有更多道具的独立组件.const Row = function(props){
const {checked, value, onChange, onChecked} = props;
return (
<div>
<input
type="checkbox"
checked={checked}
onChange={onChecked}
/>
<input type ="text" value={value} onChange={onChange}/>
</div>
);
}
class App extends React.Component {
constructor(props){
super(props);
this.state = {
rows: [
{value: 'row1', checked: false},
{value: 'row2', checked: true},
{value: 'row3', checked: false},
]
};
}
updateValue = (e, idx) => {
const rows = [...this.state.rows]; // copy array because we don't want to mutate the previous one
rows[idx].value = e.target.value;
this.setState({
rows,
});
}
onChecked = (idx) => {
const rows = [...this.state.rows]; // copy array because we don't want to mutate the previous one
rows[idx].checked = !rows[idx].checked;
this.setState({
rows,
});
}
addRow = () => {
const rows = [...this.state.rows,
{value:'', checked: false}
];
this.setState({
rows,
});
}
deleteRows = () => {
this.setState({
rows: this.state.rows.filter(e => !e.checked)
});
}
render(){
return(
<div>
{this.state.rows.map((row, idx) => {
return(
<Row
key={idx}
value={row.value}
checked={row.checked}
onChange={(e) => this.updateValue(e, idx)}
onChecked={() => this.onChecked(idx)}
/>
)
})
}
<button onClick={this.addRow}>
add
</button>
<button onClick={this.deleteRows}>
delete
</button>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.development.js"></script>
<div id="app"> </div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5824 次 |
| 最近记录: |