Javascript 如何模拟单击组件?

Javascript 如何模拟单击组件?,javascript,reactjs,Javascript,Reactjs,我在代码中使用React REF,最终目标是模拟单击选定的REF(您将看到它们在代码中的选择方式) 我试图在我的元素上使用“.click()”方法,但控制台显示我uncaughttypeerror:pinterest.click不是函数 当我在循环中记录“pinterest”变量时,我得到一个“Component”。 [![在此处输入图像描述][1][1] 这是我的密码: import React, { Component } from 'react' import InterestBox fr

我在代码中使用React REF,最终目标是模拟单击选定的REF(您将看到它们在代码中的选择方式)

我试图在我的元素上使用“.click()”方法,但控制台显示我
uncaughttypeerror:pinterest.click不是函数

当我在循环中记录“pinterest”变量时,我得到一个“Component”。 [![在此处输入图像描述][1][1]

这是我的密码:

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: []}
        this.pinterestRefs = React.createRef()
        this.pinterestRefs.current = [];
    }

    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) => {
                this.pinterestRefs.current.forEach((pinterest) => {
                    if(item == pinterest.props.id) {
                        console.log(pinterest)
                        pinterest.click();
                    }
                })
                console.log(item)
            })
        }
        console.log(this.pin)
    }

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

export default InterestList
import React,{Component}来自“React”
从“./InterestBox”导入InterestBox
从“Axios”导入Axios
导出类兴趣列表扩展组件{
建造师(道具){
超级(道具);
this.state={pinterests:[]}
this.pinterestRefs=React.createRef()
this.pinterestRefs.current=[];
}
componentDidMount(){
Axios.get()http://localhost:8000/api/interests')
。然后((成功)=>{
this.setState({pinterests:success.data.data.interests});
})
}
componentDidUpdate(prevProps){
log(JSON.stringify(prevProps));
log(JSON.stringify(this.props))
如果(this.props.alreadyChecked!=prevProps.alreadyChecked){
this.props.alreadyChecked.forEach((项)=>{
this.pinterestRefs.current.forEach((pinterest)=>{
if(item==pinterest.props.id){
console.log(pinterest)
pinterest.click();
}
})
console.log(项目)
})
}
console.log(this.pin)
}
render(){
返回(
{Object.keys(this.state.pinterests).map((兴趣,i)=>{
var pinterest=this.state.pinterests[interest];
var callbackRef=node=>this.pinterestRefs.current[i]=node;
返回
})}
)
}
}
导出默认兴趣列表
如何模拟单击

谢谢大家!

父代码:

import axios from 'axios';
import * as Cookies from 'js-cookie';
import React, { Component } from 'react';
import Button from '../../components/Button';
import Dashboard from '../Dashboard';
import ErrorContainer from '../../components/ErrorContainer';
import InterestList from '../../components/register/InterestList';

export class EditUser extends Component {
    constructor(props) {
        super(props);
        this.state = {loading: true, interests: []}
        this.addInterest = this.addInterest.bind(this);
        this.logState = this.logState.bind(this);
    }

    addInterest(id, name) {
        var mid = 'm' + id;
        console.log(this.state.interests[mid] == undefined)

        if(this.state.interests[mid] == undefined) {
            console.log(this.state);
            this.setState((state) => {
                state.interests[mid] = name;
                return {interests: state.interests}
            })
        } else {
            console.log('deleted')
            var newInterest = this.state.interests;
            delete newInterest[mid]
            this.setState({interests: newInterest})
        }
        console.log(this.state.interests)
    }

    componentDidMount() {
        var token = Cookies.get('token');
        axios.get('http://localhost:8000/api/details', {headers: {"Accept": 'application/json', "Authorization": `Bearer ${token}`}}).then(
            (success) => {
                this.setState({
                    loading: false,
                    firstname : success.data.data.user.firstname, 
                    lastname: success.data.data.user.lastname, 
                    email: success.data.data.user.email,
                    dob: success.data.data.user.dob,
                    address: success.data.data.user.address,
                    uinterests: success.data.data.interests
                })
            }, (error) => {
                this.props.history.push('/deconnexion');
            }
        )
        var places = require('places.js');
        var placesAutocomplete = places({
        appId: "plZJLSHIW8M5",
        apiKey: "0eddd2fc93b5429f5012ee49bcf8807a",
        container: document.querySelector('#address-input')
        });
    }

    logState() {
        console.log(this.state);
    }
    render() {
        return (
            <Dashboard loading={this.state.loading}>
                <h1 className="title">Modifier mon profil</h1>
                <form className="user-form offer-update-form" onSubmit={this.handleSubmit}>
                <label>Prénom :</label>
                <input type="text" name="firstname" value={this.state.firstname} onChange={this.handleChange}></input> <br />
                <label>Nom de famille :</label>
                <input type="text" name="lastname" value={this.state.lastname} onChange={this.handleChange}></input> <br />
                <label>Email :</label>
                <input type="email" name="email" value={this.state.email} onChange={this.handleChange} /><br />
                <label>Adresse :</label>
                <input type="address" id="address-input" name="address" value={this.state.address} onChange={this.handleChange} /><br />
                <label>Date de naissance :</label>
                <input type="date" name="dob" value={this.state.dob} onChange={this.handleChange} /><br />
                <InterestList alreadyChecked={this.state.uinterests} onClick={this.addInterest} />
                <ErrorContainer errors={this.state.errors} />
                <Button type="primary">Soumettre les changements</Button>
                </form>
                <Button type="danger" onClick={this.logState} />
            </Dashboard>
        )
    }
}

export default EditUser

```

CHILDREN CODE :

```
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

```


  [1]: https://i.stack.imgur.com/hHiPv.png
从“axios”导入axios;
从“js cookie”导入*作为cookie;
从“React”导入React,{Component};
从“../../components/Button”导入按钮;
从“../Dashboard”导入仪表板;
从“../../components/ErrorContainer”导入ErrorContainer;
从“../../components/register/InterestList”导入兴趣列表;
导出类EditUser扩展组件{
建造师(道具){
超级(道具);
this.state={加载:true,兴趣:[]}
this.addInterest=this.addInterest.bind(this);
this.logState=this.logState.bind(this);
}
addInterest(id、名称){
var mid='m'+id;
console.log(this.state.interests[mid]==未定义)
if(this.state.interests[mid]==未定义){
console.log(this.state);
this.setState((状态)=>{
国家利益[mid]=名称;
返回{interests:state.interests}
})
}否则{
console.log('已删除')
var newInterest=this.state.interests;
删除新利息[mid]
this.setState({interests:newInterest})
}
console.log(this.state.interests)
}
componentDidMount(){
var token=Cookies.get('token');
axios.get()http://localhost:8000/api/details“,{headers:{”Accept:'application/json',“Authorization:`Bearer${token}`})。然后(
(成功)=>{
这是我的国家({
加载:false,
firstname:success.data.data.user.firstname,
lastname:success.data.data.user.lastname,
电子邮件:success.data.data.user.email,
dob:success.data.data.user.dob,
地址:success.data.data.user.address,
u兴趣:success.data.data.interests
})
},(错误)=>{
this.props.history.push('/deconnexion');
}
)
var places=require('places.js');
var placesAutocomplete=地点({
附件:“plZJLSHIW8M5”,
apiKey:“0EDDD2FC93B5429F501EE49BCF8807A”,
容器:document.querySelector(“#地址输入”)
});
}
对数状态(){
console.log(this.state);
}
render(){
返回(
修改器mon profil
名称:

家喻户晓:
电邮:
地址:
出生日期:
索梅特雷酒店 ) } } 导出默认编辑用户 ``` 儿童代码: ``` 从“React”导入React,{Component} 导出类InterestBox扩展组件{ 建造师(道具){ 超级(道具); 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=>({ 已激活:!prevState.activated })) } 更新维度(){ log((window.getComputedStyle(this.refs.interest\u box\u content.width)) this.refs.interest\u text=(window.getComputedStyle(this.refs.interest\u box\u content).width) } render(){ 返回( {this.props.title}