如何在React中实现类似的功能?以下角度代码来自w3schools。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="firstname">
<h1>{{firstname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.lastname = "Doe";
});
</script>
<p>Change the name inside the input field, and the model data will change automatically, and therefore also the header will change its value.</p>
</body>
</html>
这是我在react中的登录页面的代码。我想修改它以反映用户输入的名称。即。如果我在“名称”字段中键入“Tyson”,我希望标题能够实时更新为“Hello Tyson”。
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Login.css';
class Login extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
constructor(props) {
super(props);
this.state = {
title: props.title,
};
}
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>
{this.state.title}
</h1>
<p className={s.lead}>Log in with your Name</p>
<form onSubmit={e => e.preventDefault()}>
<div className={s.formGroup}>
<label className={s.label} htmlFor="name">
Name
</label>
<input
className={s.input}
id="name"
type="text"
name="name"
autoFocus // eslint-disable-line jsx-a11y/no-autofocus
/>
</div>
<div className={s.formGroup}>
<label className={s.label} htmlFor="password">
Password:
</label>
<input
className={s.input}
id="password"
type="password"
name="password"
/>
</div>
<div className={s.formGroup}>
<button className={s.button}>Log in</button>
</div>
</form>
</div>
</div>
);
}
}
export default withStyles(s)(Login);
答案 0 :(得分:0)
你能发布你的其他组件吗?您通过道具传递标题,但不提供此组件。我只能猜到你想要做什么。 我不明白为什么你需要“title”作为属性,因为它总是“你好,{name}”。
登录组件:
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
password: ""
};
}
changeHandler = (value, {target: {name, type}}) => {
this.setState({[name]: value}, () => {
console.log("Your new state is:", this.state)});
}
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>
Hello, {this.state.name}
</h1>
<p className={s.lead}>Log in with your Name</p>
<form onSubmit={e => e.preventDefault()}>
<div className={s.formGroup}>
<label className={s.label} htmlFor="name">
Name
</label>
<input
className={s.input}
id="name"
type="text"
name="name"
value={this.state.name}
autoFocus // eslint-disable-line jsx-a11y/no-autofocus
onChange={this.changeHandler}
/>
</div>
<div className={s.formGroup}>
<label className={s.label} htmlFor="password">
Password:
</label>
<input
className={s.input}
id="password"
type="password"
name="password"
value={this.state.password}
onChange={this.changeHandler}
/>
</div>
<div className={s.formGroup}>
<button className={s.button}>Log in</button>
</div>
</form>
</div>
</div>
);
}
}
这是你想要做的吗?