`
sillycat
  • 浏览: 2542817 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

ReactJS(4)Forms Lifting State Up

    博客分类:
  • UI
 
阅读更多
ReactJS(4)Forms Lifting State Up

Forms
https://facebook.github.io/react/docs/forms.html
Controlled Components
class NameForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: ‘'};
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange(event) {
        this.setState({value: event.target.value});
    }
    handleSubmit(event) {
        alert('A name was submitted: ' + this.state.value);
        event.preventDefault();
    }
    render() {
        return ( <form onSubmit={this.handleSubmit}>
                        <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label>
                        <input type="submit" value="Submit" />
                    </form> );
    }
}

The textarea Tag
In ReactJS textarea use value.
<textarea value={this.state.value} onChange={this.handleChange} />

The select Tag
Instead of using this selected attribute, reactJS uses a value attribute on the root select tag.

<select value={this.state.value} onChange={this.handleChange}>
    <option value=“greapefruit”>Grapefruit</option>
    <option value=“lime”>Lime</option>
    <option value=“coconut>Coconut</option>
    <option value=“mango”>Mango</option>
</select>

Handling Multiple Inputs
Put name on the state value, it is name value pair.
class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form>
        <label>
          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
      </form>
    );
  }
}

ReactDOM.render(
  <Reservation />,
  document.getElementById('root')
);

Lifting State Up
https://facebook.github.io/react/docs/lifting-state-up.html
function BoilingVerdict(props) {
  if (props.celsius >= 100) {
    return <p>The water would boil.</p>;
  }
  return <p>The water would not boil.</p>;
}

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {temperature: ''};
  }

  handleChange(e) {
    this.setState({temperature: e.target.value});
  }

  render() {
    const temperature = this.state.temperature;
    return (
      <fieldset>
        <legend>Enter temperature in Celsius:</legend>
        <input
          value={temperature}
          onChange={this.handleChange} />
        <BoilingVerdict
          celsius={parseFloat(temperature)} />
      </fieldset>
    );
  }
}

ReactDOM.render(
  <Calculator />,
  document.getElementById('root')
);

One input changes will affect the display of another component.

Adding a Second Input
c —> Celsius
f —>  Fahrenheit

Writing Conversion Functions
function toCelsius(fahrenheit){
    return (fahrenheit - 32) * 5 / 9 ;
}

function toFahrenheit(celsius){
    return (celsius * 9 / 5) + 32;
}

function tryConvert(temperature, convert){
    const input = parseFloat(temperature);
    if(Number.isNaN(input)){
        return ‘';
    }
    const output = convert(input);
    const rounded = Math.round(output * 1000) /1000;
    return rounded.toString();
}

tryConvert('abc', toCelsius) — “”
tryConvert('10.22', toFahrenheit) — “50.296”

const scaleNames = {
  c: 'Celsius',
  f: 'Fahrenheit'
};

function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}

function toFahrenheit(celsius) {
  return (celsius * 9 / 5) + 32;
}

function tryConvert(temperature, convert) {
  const input = parseFloat(temperature);
  if (Number.isNaN(input)) {
    return '';
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

function BoilingVerdict(props) {
  if (props.celsius >= 100) {
    return <p>The water would boil.</p>;
  }
  return <p>The water would not boil.</p>;
}

class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

  handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

  handleFahrenheitChange(temperature) {
    this.setState({scale: 'f', temperature});
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (
      <div>
        <TemperatureInput
          scale="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />
        <TemperatureInput
          scale="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict
          celsius={parseFloat(celsius)} />
      </div>
    );
  }
}

ReactDOM.render(
  <Calculator />,
  document.getElementById('root')
);



References:
https://facebook.github.io/react/docs/forms.html

分享到:
评论

相关推荐

    popwav.zip_lifting_lifting scheme

    this s the sourcecode of lifting scheme

    react-dispatcher

    React分派器 ... No need in "Lifting state up" */ function reducer ( state , { type } ) { switch ( type ) { case 'INC' : return { count : state . count + 1 } ; case 'DEC' : return {

    mod_8_reactjs:Desafio ReactJS做Módulo3-GoStack 12

    4. **状态管理**:根据挑战的复杂性,可能会涉及到状态提升(lifting state up)或者使用像Redux这样的状态管理库来协调组件间的数据流。 5. **React Hooks**:React 16.8引入了Hooks,如`useState`,`useEffect`,...

    image_compress.rar_lifting_lifting wavelet_wavelet lifting_小波分解_

    标题中的“image_compress.rar”可能是一个包含图像压缩代码或程序的RAR压缩文件,而关键词“lifting”,“lifting wavelet”,“wavelet lifting”以及“小波分解”则指明了这个压缩包的内容与小波变换的提升算法...

    the fast lifting wavelet transform (权威英文原版)

    ### 快速提升小波变换(Fast Lifting Wavelet Transform) #### 概述 快速提升小波变换(Fast Lifting Wavelet Transform, FLWT)是一种高效的小波变换算法,它在1999年至2004年间由C. Valens提出并不断完善。这种...

    reactjs-burger-builder

    7. 状态提升(Lifting State Up):如果多个组件需要共享相同的状态,可以将这个状态提升到它们的共同父组件。在汉堡构建器中,可能需要在父组件中管理所有配料的选择状态。 8. 状态初始化(State Initialization)...

    Wavelets and the Lifting Scheme A 5 Minute Tour

    标题与描述均提到了“小波变换(Wavelets)”与“提升方案(Lifting Scheme)”,这是一篇关于介绍小波变换中的提升方案的文章。文章由Wim Sweldens撰写,旨在提供一个简短而深入的提升方案导览,并讨论其在构建小波...

    reactJS::books:Tudoo que estou aprendendo sobre o ReactJS

    6. **状态提升(Lifting State Up)**:当多个组件需要共享状态时,通常会将状态提升到它们的共同父组件中,通过props将状态传递下去。 7. **受控组件与非受控组件**:在表单处理中,React提供两种方式管理表单数据...

    5-3lifting

    5-3lifting 代码 dsw vc

    Adjustable lifting table.emmx

    Adjustable lifting table.emmx

    desafio01-reactjs-conceitos-do-react

    8. **状态提升(Lifting State Up)**:当多个组件需要共享状态时,将状态移至最近的共同父组件,以避免数据冗余和同步问题。 9. **优化技术**:React提供了多种性能优化手段,如PureComponent、...

    vlm.zip_VLM_lifting_propeller_propeller design_theory

    propeller design with lifting line theory

    LiftingLineTheory.zip_Lift line_lifting line_theory

    it program resolves the lifting line theory for lift estimation in 3D

    tishengfa-pragram.rar_lifting_提升小波

    标题中的“tishengfa-pragram.rar_lifting_提升小波”表明这是一个关于提升小波变换的程序包,其中“tishengfa-pragram.rar”可能是程序的压缩文件名,而“lifting”和“提升小波”是关键词,强调了这个程序的核心...

    lwt.rar_LWT-OFDM_lwt_wavelet_wavelet lifting_小波

    提升小波变换程序, %LWT Lifting wavelet decomposition 1-D. % LWT performs a 1-D lifting wavelet decomposition % with respect to a particular lifted wavelet that you specify.

    tishengxiaobo.zip_lifting_去噪_小波去噪_提升_提升小波去噪

    标题中的“tishengxiaobo.zip_lifting_去噪_小波去噪_提升_提升小波去噪”表明这是一个关于提升小波去噪技术的压缩文件,其中可能包含源代码、教程或示例程序。描述提到这是第二代提升小波去噪程序,暗示其在去噪...

    linear_2_wavelets.rar_lifting wavelet

    线性二代小波,也称为提升小波(Lifting Scheme),是小波分析领域中的一个重要概念,它提供了一种高效且灵活的实现离散小波变换的方法。与传统的滤波器组方法相比,提升方案在计算效率和内存使用上具有优势,特别...

    liftpack_double_win95.rar_lifting wavelet_liftpack_liftpack soft

    4. **双精度计算**:双精度浮点数提供了更高的数值精度,通常在需要更高精确度的科学计算中使用。 5. **应用文档**:用户可能通过提供的应用文档了解如何使用LIFTPACK进行实际问题的解决,包括理论背景、操作指南和...

    江西省赣州一中高中英语Unit4GlobalWarming单元综合测试新人教版选修6

    "lifting up"通常指提起物体,"bringing up"有抚养或提出的意思,而"growing up"则指成长。 6. 名词辨析:in a poor state of health是一个固定搭配,意为“健康状况不佳”,state在这里指的是人的健康状态。 7. ...

    细分曲面切片轮廓线的Lifting小波变换 (2005年)

    基于Lifting小波变换原理对细分曲面实体切片操作产生的离散交点序列进行...用4种不同的Lifting小波变换进行了多分辨率曲线的构造实验,并对产生的多分辨率曲线进行了对比,讨论分析了这些Lifting变换方法的性能特点。

Global site tag (gtag.js) - Google Analytics