[React] 父组件中有一组子组件, 如何将子组件中操作得到的值传回父组件并进行排序

weixin_39968394 2018-07-08 03:14:11
最近实习上遇到了一个问题,有点烦恼,一时实在想不出来。React新人,想来论坛问问大神们的想法,
是这样的,我现在有一个product table,table里面有一个接口可以得到数据,数据是一组些商品的id和相关信息,这个数据一直在变所以这些商品的个数也是变化的。
我就把商品数据 传进子组件product cell里,product.map(product => <ProductCell product={product} />这样来展现这个product table。
现在我需要在商品框product cell里有一个input小框,用来填数字,然后product table里有一个按钮,我一点击这个按钮,我就希望在table里面能得到这些商品所输入的数字和其对应的id,有了这样的一组数组ARRAY<order:Int, id: string>我就可以实现在table里面进行排序,然后把排完序的array用另一个api去save排序的信息。

我的问题是:如何在table里面得到product cell里数字的信息呢?我知道通过props里设值call back让一个子组件向父组件里传信息,但是现在有多个子组件,总个数还不确定,而且得到这些信息的触发条件在于是否在table里点击按钮。。。。。就有点搞不明白了

如果有人帅心善的大神愿意指教,十分感谢~

...全文
456 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
似梦飞花 2018-07-13
  • 打赏
  • 举报
回复

class ProductCell extends PureComponent{
constructor(props){
super(props);
this.state={
value:'',
isActive:false,
fromParent:false
}
this.changeHandle=this.changeHandle.bind(this);
}
static getDerivedStateFromProps(nextProps,preState){
if(preState.isActive){
return {isActive:!preState.isActive,fromParent:true};
}
return null;
}
changeHandle(e){
this.setState({value:e.target.value,isActive:true,fromParent:false});
}
render(){
const {id,func}=this.props;
if(this.state.fromParent){
func(id,this.state.value);
}
return[
<label>{id}</label>,
<input value={this.state.value} onChange={this.changeHandle}/>
]
}
}
class ProductTable extends Component{
constructor(props){
super(props);
this.state={
reRender:false
}
this.clickHandle=this.clickHandle.bind(this);
this.showChange=this.showChange.bind(this);
}
clickHandle(){
this.setState({reRender:true});
}
showChange(id,value){
console.log(id,value);
}
render(){
const arr=Array.from({length:this.props.length},(item,index)=>(<ProductCell func={this.showChange} key={index} id={index} />));
arr.push(<input type={'button'} value={'save'} onClick={this.clickHandle} />);
return arr;
}
}
ReactDOM.render(<ProductTable length={10}/>,document.body);
这样试试
2018-07-09
  • 打赏
  • 举报
回复
table:
onInputChange = (id, order) => {
state保存
}

onButtonClick = (e) => {
取state保存的值
}

<ProductCell onInputChange={this.onInputChange}...>

cell:
onChange = (e) => {
取当前cell的id和填的值
this.props.onInputChange(id, order);
}

<input onChange={this.onChange}

大概这个思路吧

87,841

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧