简体   繁体   English

React:如何使用React Hooks在Function组件内部添加onChange功能? 需要复选框中的onClick事件以影响输入状态

[英]React: How to add onChange functionality inside of Function component using React Hooks? Need onClick event from a checkbox to influence input state

I have a function component with a checkbox and an input. 我有一个带有复选框和输入的功能组件。 I'm trying to create an onChange function for the checkbox that clears the input and disables it whenever a user clicks it by implementing the useState React Hook. 我正在尝试为复选框创建一个onChange函数,以清除输入并在用户通过实现useState React Hook来单击它时将其禁用。 Does anyone have any experience with Hooks who's done something like this before? 有没有人对Hooks进行过类似的工作? I'm trying to look at code samples to better wrap my head around this as I'm still new to React Hooks 我试图查看代码示例以更好地解决这个问题,因为我还是React Hooks的新手。

import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import {
  Col, Row, Icon, Input, Tooltip
} from 'antd'
import Checkbox from '../elements/Checkbox'

const CustomerDetails = ({ customer }) => {
  if (customer === null) {
    return (
      <Container>
        <Row>
          <Col span={24}>
            <ErrorContainer>
              <Icon type="exclamation-circle" />
            </ErrorContainer>
          </Col>
        </Row>
      </Container>
    )
  }

  return (
    <Container>
      <h2>{customer.contact.name}</h2>
      <Row>
        <Col span={8}>
          <H3>
            <strong>Primary Contact:</strong>
          </H3>
          <P>{customer.contact.name}</P>
          <P>{customer.contact.phone}</P>
        </Col>
        <Col span={8}>
          <H3>
            <strong>Service Address:</strong>
          </H3>
          <P>{customer.site.address1}</P>
          <P>{customer.site.address2}</P>
          <P>
            {customer.site.city},&nbsp;{customer.site.state}&nbsp;
            {customer.site.postalCode}
          </P>
        </Col>
        <Col span={8}>
          <H3>
            <strong>Billing Address:</strong>
          </H3>
          <P>{customer.account.billingStreet}</P>
          <P>
            {customer.account.billingCity},&nbsp;{customer.account.billingState}
            &nbsp;
            {customer.account.billingPostalCode}
          </P>
        </Col>
      </Row>
      <br />
      <Row>
        <Col span={10}>
          <h4>
            PRIMARY CONTACT EMAIL &nbsp;
            <Tooltip
              placement="topRight"
              title={primaryContact}
            >
              <StyledTooltipIcon
                type="question-circle"
                theme="filled"
              />
            </Tooltip>
          </h4>
        </Col>
      </Row>
      <Row>
        <Col span={8}>
          <StyledInput value={customer.contact.email} />
        </Col>
        <Col span={2} />
        <Col span={8}>
          <StyledCheckbox /> EMAIL OPT OUT{' '}
          <Tooltip
            placement="topRight"
            title={emailText}
          >
            <StyledTooltipIcon
              type="question-circle"
              theme="filled"
            />
          </Tooltip>
        </Col>
      </Row>
    </Container>
  )
}

CustomerDetails.propTypes = {
  customer: PropTypes.object
}

CustomerDetails.defaultProps = {
  customer: {}
}

const Container = styled.div`
  text-align: left;
`
const StyledCheckbox = styled(Checkbox)`
  input + span {
    border-radius: 0px;
    width: 35px;
    height: 35px;
    border: 2px solid ${({ theme }) => theme.colors.black};
    background-color: transparent;
    color: ${({ theme }) => theme.colors.black};
    border-color: ${({ theme }) => theme.colors.black};
    transition: none;
  }

  input:checked + span {
    border: 2px solid ${({ theme }) => theme.colors.black};
    width: 30px;
    height: 30px;
  }

  input + span:after {
    border-color: ${({ theme }) => theme.colors.black};
    left: 20%;
    transition: none;
    width: 12.5px;
    height: 20px;
  }

  input:disabled + span:after {
    border-color: ${({ theme }) => theme.colors.gray};
  }

  input:not(:checked):hover + span:after {
    border-color: ${({ theme }) => theme.colors.gray};
    opacity: 1;
    transform: rotate(45deg) scale(1) translate(-50%, -50%);
  }

  input:focus + span {
    border-color: ${({ theme }) => theme.colors.primary};
  }
`

const StyledInput = styled(Input)`
  max-width: 100%;

  &&& {
    border: 2px solid ${({ theme }) => theme.colors.black};
    border-radius: 0px;
    height: 35px;
  }
`

const ErrorContainer = styled.div`
  /* margin-left: 25%; */
`

const StyledTooltipIcon = styled(Icon)`
  color: #1571da;
`

const H3 = styled.h3`
  white-space: nowrap;
  margin-top: 0;
  margin-bottom: 0;
  line-height: 1.5;
}
`

const H4 = styled.h4`
  text-decoration: underline;
  color: #1590ff;
`

const P = styled.p`
  margin-top: 0;
  margin-bottom: 0;
  font-size: 1rem;
`

export default CustomerDetails

You can use the useState hook to create a state variable that tracks whether the user has clicked the checkbox to disable the other input. 您可以使用useState挂钩创建状态变量,该状态变量跟踪用户是否单击了复选框以禁用其他输入。 The useState hook is a function that takes an initial value and returns a state variable and a function used to update the value of that state variable (which works pretty much the same as setState but only for a single state variable). useState钩子是一个带有初始值并返回状态变量的函数,以及一个用于更新该状态变量的值的函数(其功能与setState几乎相同,但仅适用于单个状态变量)。

For example: 例如:

const [x, setX] = React.useState(1); // `x` is initially 1, but that will change on later renders

setX(prevX => prevX + 1); // increments `x` for the next render;

You'll also need to create an event handler function to respond to the clicking of this checkbox. 您还需要创建一个事件处理程序函数来响应此复选框的单击。

Here is a full example: 这是一个完整的示例:

import React from "react";

const MyComponent = props => {
    const [disableInputIsChecked, setDisableInputIsChecked] = React.useState(false);
    const [inputValue, setInputValue] = React.useState("");

    function clearInput() {
        setInputValue("");
    }

    function handleInputChange(event) {
        setInputValue(event.target.value);
    }

    function handleCheckboxClick(event) {
        if (!disableInputIsChecked) { // this click was to check the box
            clearInput();
        }
        setDisableInputIsChecked(prevValue => !prevValue); // invert value
    }

    return (
        <form>
            <input type="checkbox" value={ disableInputIsChecked } onChange={ handleCheckboxClick }/>
            <input type="text" value={ inputValue } onChange={ handleInputChange } disabled={ disableInputIsChecked }/>
        </form>
    )
}

Here's a working example . 这是一个有效的例子

Probably you'll want to come up with better names for these values, but hopefully you get the point here. 也许您会想为这些值提出更好的名称,但希望您能明白这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在具有React钩子的复选框之一上使用onChange事件在map函数内部操作DOM - How to manipulate the DOM inside of map function using onChange event on one of the checkboxes with react hooks 如何使用 React Hooks 从子组件 onClick() 触发父组件中的事件? - How to trigger an event in Parent Component from Child Component onClick() using React Hooks? React:如何使用钩子刷新带有 onClick 的组件 - React: How to refresh a component with onClick using hooks React - 如何使用钩子来隐藏或显示基于 onChange 事件的组件 - React - how to use hooks to hide or show a component based on an onChange event 如何从需要访问 state 的 React Hooks 返回 function? - How to return a function from React Hooks that need access to the state? 如何将复选框状态传递给 React 中的 onClick 函数 - How to pass checkbox state to onClick Function in React React 钩子,使用表初始化和更改 state 和 onClick 事件 - React hooks, initialize and change state with onClick event using tables 使用回调 React Hooks 将复选框 state 转发到父组件 - Forwarding the checkbox state change to the parent component using callback React Hooks 如何使用 onClick 事件将 props 从子组件传递到父组件 React Hooks - How to use onClick event to pass the props from child component to parent component React Hooks 如何使用反应钩子等待 onChange 事件设置值? - How to wait for onChange event to set Value using react hooks?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM