React: trigger onChange if input value is changing by state?

后端 未结 9 1927
我在风中等你
我在风中等你 2020-11-30 04:34

Edit: I don\'t want to call handleChange only if the button has been clicked. It has nothing to do with handleClick. I gave an example in the @shubhakhatri

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 05:08

    Approach with React Native and Hooks:

    You can wrap the TextInput into a new one that watches if the value changed and trigger the onChange function if it does.

    import React, { useState, useEffect } from 'react';
    import { View, TextInput as RNTextInput, Button } from 'react-native';
    
    // New TextInput that triggers onChange when value changes.
    // You can add more TextInput methods as props to it.
    const TextInput = ({ onChange, value, placeholder }) => {
    
      // When value changes, you can do whatever you want or just to trigger the onChange function
      useEffect(() => {
        onChange(value);
      }, [value]);
    
      return (
        
      );
    };
    
    const Main = () => {
    
      const [myValue, setMyValue] = useState('');
    
      const handleChange = (value) => {
        setMyValue(value);
        console.log("Handling value");
      };
    
      const randomLetters = [...Array(15)].map(() => Math.random().toString(36)[2]).join('');
    
      return (
        
          
          

提交回复
热议问题