我如何使整数列表单击具有相应ID的元素?

问题描述 投票:0回答:2

我有一个ID列表(整数),并且我有多个组成部分。在向我的API请求之后,该组件会收到一个应该已经处于活动状态的ID列表。我想模拟一次单击每个ID与数组中ID相同的元素。我知道我可以使用refs来做到这一点,但我不理解如何使其与元素列表一起使用。

这是我的代码:

import React, { Component } from 'react'
import InterestBox from './InterestBox'
import Axios from 'axios'

export class InterestList extends Component {

    constructor(props) {
        super(props);
        this.state = {pinterests: []}
    }

    componentDidMount() {
        Axios.get('http://localhost:8000/api/interests')
        .then((success) => {
            this.setState({pinterests: success.data.data.interests});
        })
    }

    componentDidUpdate(prevProps) {
        console.log(JSON.stringify(prevProps));
        console.log(JSON.stringify(this.props))
        if(this.props.alreadyChecked != prevProps.alreadyChecked) {
            this.props.alreadyChecked.forEach((item) => {
                console.log(item)
            })
        }
    }

    render() {
        return (
            <React.Fragment>
                {Object.keys(this.state.pinterests).map((interest) => {
                    var pinterest = this.state.pinterests[interest];
                    return <InterestBox id={pinterest.id} onClick={this.props.onClick} icon={pinterest.picture_src} title={pinterest.name} />
                })}
            </React.Fragment>
        )
    }
}

export default InterestList
import React, { Component } from 'react'
export class InterestBox extends Component {

    constructor(props) {
        super(props);
        this.images = require('../../img/interests/*.svg');

        this.state = {activated: false};
        this.interest_box_content = React.createRef();
        this.interest_text = React.createRef();
        this.handleClick = this.handleClick.bind(this);
        this.updateDimensions = this.updateDimensions.bind(this);
    }

    handleClick() {
        this.props.handleClick(this.props.id, this.props.title);
        this.setState(prevState => ({
            activated: !prevState.activated
        }))        
    }

    updateDimensions() {
        console.log((window.getComputedStyle(this.refs.interest_box_content).width))
        this.refs.interest_text = (window.getComputedStyle(this.refs.interest_box_content).width)
    }

    render() {
        return (
            <div className="column is-one-fifth-desktop is-half-touch">
                <div className="interest-box">
                    <div className="interest-box-adjuster">
                        <div ref={"interest_box_content"} className={"interest-box-content " + (this.state.activated == true ? 'interest-box-activated' : '')} onClick={this.handleClick}>
                            <img className="interest-icon" src={this.images[this.props.icon]} style={{'height': '50%'}}></img>
                            <i className="activated-icon fas fa-check"></i>
                            <span ref={"interest_text"} className="interest-text">{this.props.title}</span>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default InterestBox

在InterestList“ componentDidUpdate”方法中,该项的值为整数。我想使用该整数在带有相应“ id”的InterestBox上“单击”。

我该如何实现?

javascript reactjs
2个回答
0
投票

您可以在一个引用中存储元素数组,如下所示:

constructor(props) {
  super(props);
  this.state = {pinterests: []}
  this.pinterestRefs = React.createRef()
}

...

render() {
        return (
            <React.Fragment>
                {Object.keys(this.state.pinterests).map((interest) => {
                    var pinterest = this.state.pinterests[interest];
                    return <InterestBox id={pinterest.id} onClick={this.props.onClick} icon={pinterest.picture_src} title={pinterest.name} ref={pinterestRef => this.refs.pinterestRefs.push(pinterestRef)} />
                })}
            </React.Fragment>
        )
    }

然后在componentDidMount函数中的每个函数上单击click函数:

componentDidMount() {
  if (this.refs.pinterestRefs.length) {
    this.refs.pinterestRefs.forEach(pinterestEl => {
      pinterestEl.click();
    });
  }
}

0
投票

由于this.pinterestRefs是引用而不是数组,所以push方法不可用。不幸的是,我们没有确定的长度,所以我们不能抢先声明引用。但是,我们可以将其添加到this.refs对象并将其转换为数组:

export class InterestList extends Component {

    constructor(props) {
        super(props);
        this.state = {pinterests: []}
    }

    componentDidMount() {
        Axios.get('http://localhost:8000/api/interests')
        .then((success) => {
            this.setState({pinterests: success.data.data.interests});
        })
    }

    componentDidUpdate(prevProps) {
        console.log(Object.values(this.refs)); // Array with all refs
        console.log(JSON.stringify(prevProps));
        console.log(JSON.stringify(this.props))
        if(this.props.alreadyChecked != prevProps.alreadyChecked) {
            this.props.alreadyChecked.forEach((item) => {
                console.log(item)
            })
        }
    }

    render() {
        return (
            {/*I'm assuming each item has a unique id, if not, create one*/}
            <React.Fragment>
                {Object.keys(this.state.pinterests).map((interest) => {
                    var pinterest = this.state.pinterests[interest];
                    return <InterestBox id={pinterest.id} onClick={this.props.onClick} ref={pinterest.id} icon={pinterest.picture_src} title={pinterest.name} />
                })}
            </React.Fragment>
        )
    }
}

export default InterestList;
© www.soinside.com 2019 - 2024. All rights reserved.