最近实习上遇到了一个问题,有点烦恼,一时实在想不出来。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里点击按钮。。就有点搞不明白了如果有人帅心善的大神愿意指教,十分感谢~

解决方案 »

  1.   

    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}大概这个思路吧
      

  2.   


    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);
    这样试试