【问题标题】:Why passing a function from a parent Class Component to a child Functional Component doesn't work?为什么将函数从父类组件传递给子功能组件不起作用?
【发布时间】:2020-04-23 15:14:33
【问题描述】:

我正在尝试将 props 中的父类组件中的方法传递给子功能组件。

父组件基本上只是将数据从数据库发送到“绘制”组件本身的功能组件。 在功能组件内部我有<option>,我想console.log()来自功能组件的数据,这意味着更改的处理程序将在类组件中,只是将它传递给子功能组件。

我在 ReactJS 文档中阅读了执行此操作的方法,但由于某种原因它不起作用。没有错误,但没有任何内容打印到控制台。

父类组件:

export default class ProductCardComponent extends Component{


  constructor(props) {
      super(props)

      this.handleClick = this.handleClick.bind(this)
      this.onChangedColor = this.onChangedColor.bind(this)

      this.state = {
          product:  [],
          currentPage: 1,
          cardsPerPage: 9,

      }
  }


onChangedColor(e) {
    console.log("sup")
    console.log(e)
    alert("here")
}



render() {



    const renderCards = currentCard.map( (card, index) => {
            return <Col key={index}> <FunctionalProductCardComponent 
                                      product={card} 
                                      key={card._id} 
                                      onChange= {(e) => this.onChangedColor(e)} />
                    </Col>
        } );

        return (
        <div id="centeredRowForPagination">
            <div>
                <Row id="RowIdForCentering">
                    {renderCards}
                </Row>
            </div>
            <div id="centeredRowForPagination">
                <Row>
                        <Pagination id="page-numbers">
                                {renderPageNumbers}
                        </Pagination>
                </Row> 
            </div>
        </div>
    )
}
}

子功能组件:

const myRef = createRef()

const FunctionalProductCardComponent = props => {



var data = [];
for (let i = 0 ; i < props.product.color.length ; i++ ) { 
    data.push( {'value': props.product.color[i], 'label': props.product.color[i] } )
}
console.log(data)
return (
    // giving the div id only for design pourpse
<div id="ProductCard">
    <Col>
        <Card style={{ width: '18rem'}}>


            <Card.Img variant="top" src={imageUrl} id='ringImgId'/>

            <Card.Body>
                <Card.Title>Card Title</Card.Title>
                <Card.Text>

                    }
                    <tr><td>Name:    {props.product.name}</td></tr>
                    <tr><td>Price: {props.product.price}</td></tr>
                    <tr><td>Gender:  {props.product.gender}</td></tr>
                    <tr><td>Serial:  {props.product.serial}</td></tr>
                </Card.Text>
            </Card.Body>

                <Accordion>
                    {/* <Card> */}
                        <Card.Header>
                        <Accordion.Toggle className="accordionToggleButton" as={Button} variant="link" eventKey="0">
                            Size :
                        </Accordion.Toggle>
                        </Card.Header>
                        <Accordion.Collapse eventKey="0">
                            {/* <Card.Body> */}
                                <Select  ref={myRef} required className='form-control' options={props.product.size} placeholder ={'Select a color'} onChange={(selectedValue) => { props.onChange(()=>{{return selectedValue}}); }} />
                                    {/* <Select className="form-control" options={props.product.size} onChange= {(selectedValue) => {
                                        this.setState({value: selectedValue});
                                        this.props.onChange(() => {return selectedValue})
                                    }} 
                                    // value={this.state.value}
                                     /> */}
                            {/* </Card.Body> */}
                        </Accordion.Collapse>
                    {/* </Card> */}
                    {/* <Card> */}
                        <Card.Header>
                        <Accordion.Toggle className="accordionToggleButton" as={Button} variant="link" eventKey="1">
                            Color : 
                        </Accordion.Toggle>
                        </Card.Header>
                        <Accordion.Collapse eventKey="1">
                            <Card.Body>
                                <Select required className='form-control' options={data} placeholder ={'Select a color'} onChange={(selectedValue) => { props.onChange(()=>{{return selectedValue}}); }} />
                            </Card.Body>
                        </Accordion.Collapse>
                    {/* </Card> */}
                </Accordion>
                {/* () => {
      return selectedValue;
    } */}
            <Card.Body>
                <Card.Link href="#">Buy</Card.Link>
                <Card.Link id="addToCartBtn" href="#">Add To Cart</Card.Link>
            </Card.Body>


        </Card>
    </Col>
</div>

) }

导出默认的FunctionalProductCardComponent;

它现在调用方法,但不传递值。

【问题讨论】:

  • 请把这个删减成minimal reproducible example(笑话cmets可以开始了!)
  • @jonrsharpe 我编辑了,这个笑话来自它自己的代码,不打算在这里发布。我忘了我写的。 :)
  • 你从来没有在子进程中引用props.onChange,所以不清楚你为什么期望调用父函数。
  • @jonrsharpe 我做了,但我尝试了其他方法,当我参考props.onChange时它仍然不起作用,再次编辑。
  • 所以给minimal reproducible example(这里还有很多代码)尝试一下可能会起作用。想想你传递的道具的实际名称是什么。

标签: javascript reactjs


【解决方案1】:

ProductCardComponent 组件中:

onChange= {(e) =&gt; this.onChangedColor(e)}

应该替换为

onChange ={(e)=&gt; {this.onChangedColor(()=&gt; {return e()})}}//e is a function

然后从FunctionalProductCardComponent,在

this.props.onChange(()=&gt;{return selectedValue});

匿名函数返回onChangedColor()使用的值

这就是为什么它的参数应该作为一个函数来处理:

onChangedColor(e) {
    console.log("sup")
    console.log(e()) //e is a function passed in FunctionalProductCardComponent
    alert("here")
}`

【讨论】:

猜你喜欢
  • 2020-02-09
  • 2017-08-04
  • 1970-01-01
  • 2017-10-10
  • 2021-11-06
  • 2021-01-26
  • 1970-01-01
  • 2021-09-12
  • 2020-02-04
相关资源
最近更新 更多