javascript - 动态显示替代文字
问题描述
我正在尝试用 react 更好地理解状态,如果你问我,这是一个很好的例子。
动态我的意思是:在表单中输入的同时渲染下面的输出。
class Demo extends Component {
constructor(props) {
super(props);
this.state = {
input: "",
output: "",
}
}
render() {
const smallCaps = {
'a' : 'ᴀ',
'b' : 'ʙ',
'c' : 'ᴄ',
'd' : 'ᴅ',
'e' : 'ᴇ',
'f' : 'ғ',
'g' : 'ɢ',
'h' : 'ʜ',
'i' : 'ɪ',
'j' : 'ᴊ',
'k' : 'ᴋ',
'l' : 'ʟ',
'm' : 'ᴍ',
'n' : 'ɴ',
'o' : 'ᴏ',
'p' : 'ᴘ',
'q' : 'ǫ',
'r' : 'ʀ',
's' : 's',
't' : 'ᴛ',
'u' : 'ᴜ',
'v' : 'ᴠ',
'w' : 'ᴡ',
'x' : 'x',
'y' : 'ʏ',
'z' : 'ᴢ',
};
function strtr(s, p, r) {
return !!s && {
2: function () {
for (var i in p) {
s = strtr(s, i, p[i]);
}
return s;
},
3: function () {
return s.replace(RegExp(p, 'g'), r);
},
0: function () {
return;
}
}[arguments.length]();
}
const input = 'this is a test'
const style = smallCaps;
let outputt = strtr(input, style);
console.log(outputt);
return (
<div>
<div>
<Form
style={{ width: 300 }}
>
<Form.Item>
<Input id="input" placeholder="input text" />
</Form.Item>
</Form>
</div>
</div>
<div>
<div>
Style One:
<div>
{this.state.output}
</div>
</div>
</div>
如果有人能指出我正确的方向,我将不胜感激!
最终我希望能够一次显示多种样式,但我首先想了解这一点。
解决方案
每次您的输入更改时,它都会触发一个 onChange 回调,您可以在其中获取元素的值以更新状态:
const smallCaps = {
'a' : 'ᴀ',
'b' : 'ʙ',
'c' : 'ᴄ',
'd' : 'ᴅ',
'e' : 'ᴇ',
'f' : 'ғ',
'g' : 'ɢ',
'h' : 'ʜ',
'i' : 'ɪ',
'j' : 'ᴊ',
'k' : 'ᴋ',
'l' : 'ʟ',
'm' : 'ᴍ',
'n' : 'ɴ',
'o' : 'ᴏ',
'p' : 'ᴘ',
'q' : 'ǫ',
'r' : 'ʀ',
's' : 's',
't' : 'ᴛ',
'u' : 'ᴜ',
'v' : 'ᴠ',
'w' : 'ᴡ',
'x' : 'x',
'y' : 'ʏ',
'z' : 'ᴢ',
};
class Demo extends React.Component {
constructor() {
super();
this.state = {
value: "",
output: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const text = (event.target.value);
const changedText = strtr(text, smallCaps);
this.setState({value: text, output: changedText});
}
render() {
return (<div>
<h3>input:</h3>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<p>{this.state.output}</p>
</div>);
}
}
React.render(<Demo />, document.getElementById('app'));
function strtr(s, p, r) {
return !!s && {
2: function () {
for (var i in p) {
s = strtr(s, i, p[i]);
}
return s;
},
3: function () {
return s.replace(RegExp(p, 'g'), r);
},
0: function () {
return;
}
}[arguments.length]();
}
推荐阅读
- python - 基于 CSV 的登录系统问题
- protractor - E/launcher - 进程退出,错误代码为 100
- php - 我的 ajax 调用得到了正确的响应,但没有做任何事情
- python - 在 Python 中对“命令式外壳,功能核心”进行单元测试时遇到问题
- makefile - 生成文件到 CodeLite
- cakephp - Cake : 未能打开 stream() 权限
- python - 在 python 中执行代码时如何更改 URL 中的脚本名称
- c# - 访问类库中的文件
- android - 使用 NDK r17c 将 VTK 添加到 Android Studio 3.3 项目
- webpack - 我在使用 Dockerfile 构建反应应用程序和 webpack 时遇到问题