【问题标题】:TypeError: Cannot read property 'onMouse' of undefined React Class ComponentTypeError:无法读取未定义的 React 类组件的属性“onMouse”
【发布时间】:2021-09-20 15:12:44
【问题描述】:

当用户单击输入元素并且表单中的按钮元素将从麦克风图标更改为发送图标时,我想这样做。我的想法是从 onClick 或 mouseEnter 处理程序中获取值并将其传递给 if-else 语句并设置正确的图标

这是我的代码 `

import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form';
import InsertEmoticonIcon from '@material-ui/icons/InsertEmoticon';
import AttachFileIcon from '@material-ui/icons/AttachFile';
import MicIcon from '@material-ui/icons/Mic';
import SendIcon from '@material-ui/icons/Send';

import styled from 'styled-components'
import './MessageSender.css'

export class MessageSender extends Component {

constructor(props){
    super(props);
    this.state = {
        bool: 'false'
    }
    this.onMouse = this.onMouse.bind(this);
}


onMouse(){
    this.setState({bool: "true"})
}

renderInput(formProps){
    
    return <input 
        onChange={formProps.input.onChange}
        value={formProps.input.value}
        placeholder="Message" 
        onClick={this.onMouse()}
    />
}

onSubmit(formValues){
    console.log(formValues);
}
check(){
    // return <Send />
    if(this.state.bool === 'true'){
        return <Send />
    }else{
        return <Mic />
    }
}

render() {
    return (
            <form autoComplete="off" onSubmit={this.props.handleSubmit(this.onSubmit)}>
                <Emotion />
                <Field  name="Message" component={this.renderInput} placeholder="Message"  />
                <Attach />
                <button>
                    {this.check()}
                </button>
            </form>
        
    )
}
}

const Emotion = styled(InsertEmoticonIcon)`
    width: 40px!important;
    height: 40px!important;
    color: rgb(170,170,170);
`

const Attach = styled(AttachFileIcon)`
    width: 40px!important;
    height: 40px!important;
    color: rgb(170,170,170);
    margin-right: 0.3rem;
`
const Mic = styled(MicIcon)`

`
const Send = styled(SendIcon)`

`

export default  reduxForm({
    form: 'message'
})(MessageSender);

`

因此,这是我的Error

请帮帮我,谢谢!

【问题讨论】:

    标签: javascript reactjs typescript react-redux ecmascript-2017


    【解决方案1】:

    试试这个。我认为使用箭头函数可以解决使用this 的问题。当你将它传递给onClick时,你不应该调用这个函数

    renderInput = (formProps) => {
        
        return <input 
            onChange={formProps.input.onChange}
            value={formProps.input.value}
            placeholder="Message" 
            onClick={this.onMouse}
        />
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 2021-09-24
      • 2020-07-10
      • 2019-07-07
      • 2021-03-10
      • 2020-02-10
      • 2021-04-17
      • 1970-01-01
      相关资源
      最近更新 更多