如何在选择框中选择value
时链接到onChange
?
希望将select
菜单实施到链接到value
onChange
的 ReactJS 。
render() {
return (
<select onChange={() => {if (this.value) window.location.href=this.value}}>
<option value="">Please select</option>
{pages.map(({ node: page })=> (
<option key={page.id} value="{page.slug}">{page.title}</option>
))}
</select>
);
}
这是获得价值(我相信),但我不断得到Cannot read property 'value' of undefined
我已尝试按照某些答案中的建议使用文档here但我无法使用当前代码 - 请参阅完整的Page.js
import React from 'react'
import Helmet from 'react-helmet'
import styled from 'styled-components'
import config from '../utils/siteConfig'
const PageCompany = ({data}) => {
const {title,slug} = data.contentfulCompanyPage;
const pages = data.allContentfulCompanyPage.edges;
return(
<Wrapper>
<CompanyMenu>
<div>
<select onChange={() => {if (this.value) window.location.href=this.value}}>
<option value="">Please select</option>
{pages.map(({ node: page })=> (
<option key={page.id} value="{page.slug}">{page.title}</option>
))}
</select>
</div>
</CompanyMenu>
</Wrapper>
)
}
export const companyQuery = graphql`
query companyQuery($slug: String!) {
contentfulCompanyPage(slug: {eq: $slug}) {
title
slug
keywords
description
heroBg {
sizes(maxWidth: 1500) {
src
}
}
}
allContentfulCompanyPage(sort: {fields: [menuOrder], order: ASC}) {
edges {
node {
id
title
slug
}
}
}
}
`
export default PageCompany
答案 0 :(得分:1)
您可以创建一个单独的方法./fabricDev.sh start
,而不是使用全局window.location
属性:
handleChange
编辑:为了使用constructor(props) {
super(props);
this.state = { }; // initialise state
// Make sure to bind handleChange or you can make use of arrow function
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
const targetValue = e.target.value;
// Then you can do whatever you want to do with the value
this.setState({
[name]: targetValue
});
,请确保使用constructor
语法定义组件,如:
class
在 import React , { Component } from 'react';
class PageCompany extends Component {
constructor(props) {
super(props);
this.state = { }; // initialise state
this.handleChange = this.handleChange.bind(this);
}
// Make sure class has a render method
render () {
return ()
}
}
内,您可以将其引用到<Select>
handleChange
您可以阅读有关onChange Here
的更多信息答案 1 :(得分:0)
您需要传递img
参数,然后从该事件的目标中获取值,例如
event
这是一个很好的例子here 链接文档的完整代码摘录:
onChange={(event) => this.setState({value: event.target.value})}