Bruce
Bruce

Reputation: 1695

Why the span value didn't bind with input in react.js?

when I changed input value,span value didn't match with my expected change. here is my jsx file:

import React from 'react';
import styles from './Avatar.less';
import { Input } from 'antd';

var typed = '';

function changed(e){
    console.log(typed);
    typed = e.target.value;
}

const Avatar = () => {
  return (
    <div className={styles.normal}>
     <span>{typed}</span>
     <Input onChange={changed.bind(this)} placeholder="text in" />
    </div>
  );
};

export default Avatar;

Upvotes: 1

Views: 5224

Answers (2)

Sergio
Sergio

Reputation: 28845

Use React's state functionality so it will re-render when the value of type changes. Basically your app could look like this:

const {Input} = antd;

class Avatar extends React.Component {
	constructor() {
		super();
		this.state = {style: ''};
	}
	onChange(e) {
		this.setState({typed: e.target.value});
	}
	render() {
		return ( 
			<div className="normal">
				<span>{this.state.typed}</span>
				<Input onChange={this.onChange.bind(this)} placeholder="text in" />
			</div>
		);
	}
}

ReactDOM.render(
	<Avatar/>,
	document.getElementById('app')
);
.normal > * {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://npmcdn.com/antd/dist/antd.js"></script>

<div id="app"></div>

Upvotes: 1

Ross Khanas
Ross Khanas

Reputation: 1501

Because you change a typed variable, which does not trigger component re-rendering.

You need to read the react tutorial about a component life-cycle. For triggering component update you usually need to change the state or pass new properties.

Here is a working example for you.

Upvotes: 0

Related Questions