最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change a variable value in react on button click - Stack Overflow

programmeradmin1浏览0评论

When someone clicks on "Add more" button, I want the pickers variable to change (contain two instances of mainPart.

On page load, there is only one mainPart inside pickers. But I want to change it when someone clicks on "Add more".

I have a react code like this:

export default class TestComponent extends React.Component {
    constructor(props) {
        // Stuff here
    }
  
    mainPart(a,b,c) {
        return (
            // Stuff here
        )
    }
    
    changeMyVariable(a,b,c,type) {
        if (type==1) {
            return [
                ( 
                    <span>
                        mainPart(a,b,c)
                    </span>
                )
            ]
        }
        if (type==2) {
            return [
                ( 
                    <span>
                        mainPart(a,b,c)
                    </span>
                ),
                ( 
                    <span>
                        mainPart(a,b,c)
                    </span>
                )
            ]
        }
    }
    
    render() {
        let pickers = this.changeMyVariable(a, b, c,1);
        
        return (
            {pickers}
            <button onClick={this.changeMyVariable(a, b, c,2)} type="button">Add more</button>
        );
        
    }
}

When someone clicks on "Add more" button, I want the pickers variable to change (contain two instances of mainPart.

On page load, there is only one mainPart inside pickers. But I want to change it when someone clicks on "Add more".

I have a react code like this:

export default class TestComponent extends React.Component {
    constructor(props) {
        // Stuff here
    }
  
    mainPart(a,b,c) {
        return (
            // Stuff here
        )
    }
    
    changeMyVariable(a,b,c,type) {
        if (type==1) {
            return [
                ( 
                    <span>
                        mainPart(a,b,c)
                    </span>
                )
            ]
        }
        if (type==2) {
            return [
                ( 
                    <span>
                        mainPart(a,b,c)
                    </span>
                ),
                ( 
                    <span>
                        mainPart(a,b,c)
                    </span>
                )
            ]
        }
    }
    
    render() {
        let pickers = this.changeMyVariable(a, b, c,1);
        
        return (
            {pickers}
            <button onClick={this.changeMyVariable(a, b, c,2)} type="button">Add more</button>
        );
        
    }
}
Share Improve this question asked Nov 18, 2020 at 16:52 RahulRahul 1471 gold badge2 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Firstly You need to use state to make your ponent render when type changes

constructor(props){
    super(props)
   this.state = {
     type: 1
  }
}

render(){
    let pickers  =  this.changeMyVariable(a, b,  c,  this.state.type);
   return (<>{pickers}
<button onClick={() => this.setState({type: 2})} /></>
);
}

Secondly You didn't handle button click event very well before. Your function would run immediately after render not on button click.

Here is the full example using functional ponent and useState and useEffect hooks.


import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './ponents/AssetExample';

// or any pure javascript modules available in npm
const App = () => {
  const [pickers, setPickers] = useState([]);

  const mainPart = (a, b, c) => {
    return <p>{`${a} ${b} ${c}`}</p>;
  };

  const changeMyVariable = (a, b, c, type) => {
    if (type === 1) {
      setPickers([...pickers, <p>pressed {type}</p>, mainPart(a, b, c)]);
    }
    if (type === 2) {
      setPickers([
        ...pickers,
        <p>pressed {type}</p>,
        mainPart(a, b, c),
        mainPart(a, b, c),
      ]);
    }
  };

  useEffect(() => {
    changeMyVariable('one default', 'two default', 'three default', 1);
  }, []);

  return (
    <>
      {pickers}
      <button
        onClick={() => changeMyVariable('one', 'two', 'three', 1)}
        type="button">
        Add one
      </button>
      <br></br>
      <button
        onClick={() => changeMyVariable('one', 'two', 'three', 2)}
        type="button">
        Add two
      </button>
    </>
  );
};

export default App;

Screenshot:

Live Demo of App : Expo Snack

also, i would to remend take a look about useState, other hooks to make it more easer.

import React from "react";

export default class TestComponent extends React.Component {
  constructor(props) {
    // Stuff here
  }

  mainPart = (a, b, c) => {
    return <h1>Ok1</h1>;
  };

  changeMyVariable = (a, b, c, type) => {
    if (type === 1) {
      return <span>mainPart(a,b,c)</span>;
    } else {
      return (
        <>
          <span>mainPart(a,b,c)</span>
          <span>mainPart(a,b,c)</span>
        </>
      );
    }
  };

  render() {
    let pickers = this.changeMyVariable(a, b, c, 1);

    return (
      <>
        {pickers}
        <button
          type="button"
          onClick={() => {
            this.changeMyVariable(a, b, c, 2);
          }}
        >
          Add more
        </button>
      </>
    );
  }
}
发布评论

评论列表(0)

  1. 暂无评论